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

【leetcode】203 - Remove Linked List Elements

时间:2015-08-02 23:00:31      阅读:103      评论: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

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

 

【leetcode】203 - Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/irun/p/4696817.html

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