当前位置:网站首页>Leetcode question brushing record | 203_ Remove linked list elements

Leetcode question brushing record | 203_ Remove linked list elements

2022-07-06 07:53:00 coder_ sure


author github link github link

Force to buckle 203 topic

type : Linked list

subject :

Give you a list of the head node head And an integer val , Please delete all the contents in the linked list Node.val == val The node of , And back to New head node .

Example 1

 Insert picture description here

 Input :head = [1,2,6,3,4,5,6], val = 6
 Output :[1,2,3,4,5]

Example 2

 Input :head = [], val = 1
 Output :[]

Example 3

 Input :head = [7,7,7,7], val = 7
 Output :[]

Their thinking

Train of thought reminder : Three nodes are used to traverse
Train of thought details :

  1. Define a temporary node dummy, Put it at the beginning of the whole linked list ( because head Move backward , The value in front of the linked list is lost )
  2. dummy.next Point to head
  3. Define another variable prev, Responsible for following head The last linked list to be generated is reserved one by one
Created with Raphaël 2.3.0 Judge head.val Is it equal to val? prev.next = head.next ;head = head.next prev = head;head = head.next yes no
  1. Until the traversal is complete , return dummy.next

python

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if head is None :
            return None
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy
        while(head!=None):
            if head.val == val:
                prev.next = head.next
                head=head.next
            else:
                prev = head
                head = head.next
        return dummy.next

c++

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
    
public:
    ListNode* removeElements(ListNode* head, int val) {
    
        if(!head) return NULL;
        ListNode * dummy = new ListNode(0);
        dummy -> next = head;
        ListNode * prev=dummy;
        while(head!=NULL){
    
            if(head->val==val){
    
                prev->next = head->next;
                head = head->next;
            }
            else{
    
                prev = head;
                head = head->next;
            }

        }
        return dummy->next;
    }
};
原网站

版权声明
本文为[coder_ sure]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131850390936.html