LeetCode203:Remove Linked List Elements

来源:互联网 发布:ansys15.0软件 编辑:程序博客网 时间:2024/06/03 16:49

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;    }};


0 0
原创粉丝点击