[LeedCode OJ] #203 Remove Linked List Elements,
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Link: https://leetcode.com/problems/remove-linked-list-elements/
Question:
Given a linked list and a number of x, it is required to delete all the nodes equal to x in the linked list and return the new linked list.
Ideas:
It's easy to directly traverse the entire linked list. Once the same node as x is found, it will be skipped directly. Be careful when dealing with several consecutive nodes that are equal to x.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public:ListNode* removeElements(ListNode* head, int val){while(head && head->val==val)head = head->next;ListNode *cur = head;ListNode *newlist = new ListNode(0);ListNode *ptr = newlist;while(cur){while(cur && cur->val == val)cur = cur->next;if(cur==nullptr)break;ListNode *pnext = cur->next;ptr->next = cur;cur = pnext;ptr = ptr->next;}ptr->next = nullptr;return newlist->next;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source