您的位置:首页 > Web前端 > Node.js

LeetCode-203. Remove Linked List Elements

2017-03-03 11:02 295 查看
问题:

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