剑指Offer? 18
相比于原有的移除链表中元素,其只有一个结点需要移除,因此代码相比于原题有所改变,需要加上一行代码?
该题代码如下
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode * DummyHead = new ListNode(0);
DummyHead->next = head;
ListNode * cur = DummyHead;
if(cur->next == NULL){
return 0;
}
if(cur->next->val == val){
return cur->next->next;
} //此处为相比于之前的题目加上的代码
while(cur->next != nullptr ){
if(cur->next->val == val){
ListNode * Temp = cur->next;
cur->next = cur->next->next;
delete Temp;
}
else{
cur = cur->next;
}
}
head = DummyHead->next;
delete DummyHead;
return head;
}
};
|