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

[Leetcode] Remove Linked List Elements

时间:2015-04-23 21:15:15      阅读:123      评论: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.

 

 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 == NULL) return NULL;
13         ListNode *cur = head, *next = head->next;
14         while (next != NULL) {
15             if (next->val == val) {
16                 cur->next = next->next;
17                 delete next;
18                 next = cur->next;
19             } else {
20                 cur = cur->next;
21                 next = next->next;
22             }
23         }
24         if (head->val == val) {
25             cur = head;
26             head = head->next;
27             delete cur;
28         }
29         return head;
30     }
31 };

 

[Leetcode] Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4451483.html

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