LeetCode203:Remove Linked List Elements

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


原文地址:https://www.cnblogs.com/jzssuanfa/p/6721392.html