题目描述
删除链表中等于给定值 *val* 的所有节点。
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解题思路
简单题,技巧是设置一个dummyHead
节点,最后返回dummyHead->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 == nullptr)
return nullptr;
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* pNode = dummyHead;
while(pNode != nullptr){
while(pNode->next != nullptr && pNode->next->val == val){ // 这里要是while才行,避免 “[1,1] , 1” 这种情况出现错误
ListNode* pDel = pNode->next;
pNode->next = pNode->next->next;
delete pDel;
pDel = nullptr;
}
pNode = pNode->next;
}
return dummyHead->next;
}
};