LeetCode-203. Remove Linked List Elements

来源:互联网 发布:unity3d 源代码 编辑:程序博客网 时间:2024/06/03 18:25

问题:
https://leetcode.com/problems/remove-linked-list-elements/?tab=Description
Remove all elements from a linked list of integers that have value val.
删除值为val的元素。
Example: Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6 Return: 1 –> 2 –> 3 –> 4 –> 5
分析:
注意删除头结点的情况。
参考C++代码:

/** * 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* pre=head;         ListNode* cur=head;         if(head==NULL) return head;         while(cur!=NULL){             if(head->val==val){                 head=head->next;                 cur=head;                 pre=head;                 continue;             }             if(cur->val==val){                 pre->next=cur->next;                 cur=cur->next;                 continue;             }             pre=cur;             cur=cur->next;         }         return head;    }};
0 0