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

Remove Linked List Elements

时间:2015-10-08 10:36:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Wrong Edition.

技术分享
 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         if(!head) return head;
13         if(!head->next) return head->val == val ? NULL : head;
14         
15         while(head->val == val)
16             head = head->next; //avoid the case where continuous val at the head
17         if(!head) return NULL;
18         
19         ListNode* current = head;
20         while(current){
21             if(current->next->val == val){
22                 ListNode* temp = current->next;
23                 while(temp && temp->val == val)
24                     temp = temp->next;
25                 current->next = temp;
26             }
27             current = current->next;
28         }
29         return head;
30     }
31 };
View Code

 

Runtime: 36ms

 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         if(!head) return head;
13         
14         ListNode* pre = new ListNode(0);
15         pre->next = head;
16         ListNode* move = pre;
17         
18         while(move->next){
19             if(move->next->val == val)
20                 move->next = move->next->next;
21             else
22                 move = move->next;
23         }
24         return pre->next;
25     }
26 };

 

Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4860045.html

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