首页 > 代码库 > 203. Remove Linked List Elements
203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Solution 1: add a sentinel to make the two conditions removing at the beginning and removing in the middle to be one condition.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 ListNode* sentinel=new ListNode(-1); 13 ListNode* pre=sentinel, *cur=head; 14 sentinel->next=head; 15 while(cur){ 16 if (cur->val==val){ 17 pre->next=cur->next; 18 cur=pre->next; 19 } 20 else { 21 cur=cur->next; 22 pre=pre->next; 23 } 24 } 25 return sentinel->next; 26 } 27 };
Solution 2: only use one pointer. line 10 free the memory of the deleted node to avoid the memory leak.
1 class Solution { 2 public: 3 ListNode* removeElements(ListNode* head, int val) { 4 ListNode* sentinel=new ListNode(-1), *pre=sentinel; 5 sentinel->next=head; 6 while(pre->next){ 7 if (pre->next->val==val){ 8 ListNode* delptr=pre->next; 9 pre->next=pre->next->next; 10 delete delptr; 11 } 12 else pre=pre->next; 13 } 14 return sentinel->next; 15 } 16 };
203. Remove Linked List Elements
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。