一、题目描述:203. 移除链表元素(简单)
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
二、解题思路
1、定义head指针和next指针,表示当前
2、先通过while循环,判断如果head->value == value则head和next都往下走。直到head元素不等于val
3、通过while循环,如果next->val == val则删除next。即head->next = next->next,next= next->next;
三、代码
/**
* 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 * next = head->next;
while(head != NULL && head->val == val )
{
head = next;
if(next != NULL)
next = head->next;
}
ListNode * r = head;
while(next != NULL)
{
if(next->val == val)
{
head->next = next->next;
next = next->next;
}
else
{
head = next;
next = next->next;
}
}
return r;
}
};