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

LeetCode Remove Linked List Elements 删除链表元素

时间:2015-04-25 22:31:03      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

 

题意:移除链表中元素值为val的全部元素。

思路:算法复杂度肯定是O(n),那么就在追求更少代码和更少额外操作。我做不出来。

 

技术分享
 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         while(head&&head->val==val)    head=head->next;
13         if(!head)    return 0;
14         ListNode *tmp=head;
15         while(head&&head->next)
16         {
17             if(head->next->val==val)
18                 head->next=head->next->next;
19             else
20                 head=head->next;
21         }
22         return tmp;
23     }
24 };
Remove Linked List Elements

 

LeetCode Remove Linked List Elements 删除链表元素

标签:

原文地址:http://www.cnblogs.com/xcw0754/p/4456808.html

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