203(移除链表元素)
写这道题的时候本来以为能够很顺利的AC,然后发现没通过,然后一直检查bug,这改改那改改。最后还是看了答案才发现错误,还是对链表的理解不够深刻。
//自己最初写的有bug的代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != NULL){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
cur = cur->next; //出错的位置
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
//正确写法
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != NULL){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}else{
cur = cur->next; //if语句后面要加上else
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
707 (设计链表)
这题之前做的时候一直有小错误
这次直接AC!开心