您的位置:首页 > 其它

LeetCode(203) Remove LinkedList Elements

2015-11-03 13:23 225 查看

题目

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.

分析

删除链表中的指定值的节点。

需要注意的是,所需要删除节点的位置,头,中间,尾,不同位置需要不同处理,避免断链~

AC代码

/**
* 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) {
if (head == NULL)
return head;

ListNode *pre = head, *p = head;
while (p)
{
//找到要删除的节点元素
if (p->val == val)
{
//判断当前节点为头结点
if (p == head)
{
head = p->next;
ListNode *q = p;
//更新头
p = head;
pre = head;
delete q;
q = NULL;
}
//删除尾节点
else if (p->next == NULL)
{
pre->next = NULL;
delete p;
p = NULL;
}
//删除链表中间节点
else{
pre->next = p->next;

ListNode *q = p;
p = p->next;
delete q;
q = NULL;
}//else
}//if
else{
pre = p;
p = p->next;
}

}//while
return head;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: