首页 > 其他 > 详细

LeetCode203:Remove Linked List Elements

时间:2015-07-24 18:35:41      阅读:294      评论: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.

这道题需要使用一个指向头节点的指针的小技巧,否则需要特别第处理头指针,处理会复杂很多。

使用一个指向头节点的指针,这样就能将这个处理过程统一起来。遍历时使用两个指针,一个指向当前节点,一个指向当前节点的前一个节点。当当前节点的值与val的值不同时,更新两个指针的值;当当前节点的值和val值相同时,删除当前节点,同时更新这两个指针。

技术分享

runtime:32ms

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
       ListNode * pRoot=new ListNode(0);
       pRoot->next=head;
       ListNode * cur=head;
       ListNode * pre=pRoot;
       while(cur)
       {
           if(cur->val!=val)
           {
               pre=cur;
               cur=cur->next;
           }
           else
           {
               pre->next=cur->next;
               cur=pre->next;
           }
       }
       return pRoot->next;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode203:Remove Linked List Elements

原文:http://blog.csdn.net/u012501459/article/details/47041955

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!