删除链表中等于给定值 val 的所有节点。
示例 :
输入 : 1->2->6->3->4->5->6, val = 6
输出 : 1->2->3->4->5
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
思路:定义两个指针(比如pPre,pCur),让pPre指向头结点,让pCur指向头的下一个结点,然后一起向前走,找值为val的节点。找到后更新pPre,删除pCur指向的结点就好了。当然,头结点值可能也是val,我们最后再判断,然后看是否要删除就好
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (!head)return head;
struct ListNode* pPre = head;
struct ListNode* pCur = pPre->next;
while (pCur)
{
if (pCur->val == val)
{
pPre->next = pCur->next;
pCur = pPre->next;
}
else
{
pPre = pCur;
pCur = pCur->next;
}
}
if (head->val == val)
head = head->next;
return head;
}
};