您的位置:首页 > 其它

[leetcode] 203. Remove Linked List Elements

2015-12-01 19:46 260 查看
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

这道题比较简单,删除链表中值是指定值的节点,题目难度为easy。

处理起来比较简单,所以这里不推荐递归的做法,就不列出递归的代码了。唯一需要注意的是链表头节点需要删除时head的赋值。具体代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* cur = head;
ListNode* pre = NULL;

while(cur) {
if(cur->val == val) {
if(cur == head) head = head->next;
if(pre) pre->next = cur->next;
}
else {
pre = cur;
}
cur = cur->next;
}

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode