Note:
因为头结点是有可能发生改变的,先创建一个虚拟头结点,然后去枚举下一个位置,判断是否应该删掉
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
auto dummy = new ListNode(-1);
dummy -> next = head;
for(auto cur = dummy; cur -> next; cur = cur -> next)
if(cur -> next -> val == val){
cur -> next = cur -> next -> next;
break;
}
return dummy -> next;
}
};