您的位置:首页 > 其它

LeetCode203:Remove Linked List Elements

2015-07-24 15:46 507 查看
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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: