码迷,mamicode.com
首页 > 其他好文 > 详细

203. Remove Linked List Elements

时间:2017-06-18 10:28:34      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:solution   turn   ddl   sentinel   void   beginning   lis   ret   from   

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

标签:solution   turn   ddl   sentinel   void   beginning   lis   ret   from   

原文地址:http://www.cnblogs.com/anghostcici/p/7042933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!