#LeetCode 203
This problem let us remove linked list elements.
Problem description:
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.


I will give two ways to solve this problem.
/**
* 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 will be removed element in the first node
while (head && head -> val == val)
head = head -> next; //Update the head node
ListNode* cur = head; //Define a pointer,we should keep the head of linked list
while (head && head -> next)
{
//Check the next value of node
if (head -> next -> val == val) //If the value==target value
//Let the current node point to next node of target node
head -> next = head -> next -> next;
else head = head -> next; //Otherwise, update the current node
}
return cur; //return the head of linked list
}
};
The other way is to set a dummy node.
/**
* 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) {
ListNode* dummy = new ListNode; //Create a new node, don't care about its value
dummy -> next = head; //Let the new node become the head of linked list
ListNode* cur = dummy; //Let a pointer point to the head
//While loop condition: the real head of linked list is not NULL
while(cur -> next)
{
//Check the next node value,if value==target value
if (cur -> next -> val == val)
//Change the current node point to the next of target node
cur -> next = cur -> next -> next;
else cur = cur -> next; //Otherwise, update the pointer
}
//Return the real head of linked list
return dummy -> next;
}
};
Wish the tutorial can help you!
让思维见见世面
浙公网安备 33010602011771号