文章來源:http://www.zghlxwxcb.cn/news/detail-835684.html
思路:不同的情況出現(xiàn)了,就是第一個節(jié)點要是為等于val的節(jié)點,可以新建一個節(jié)點,并next指向head,這樣就可以遍歷新的鏈表來刪除節(jié)點文章來源地址http://www.zghlxwxcb.cn/news/detail-835684.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//如果為空鏈表則返回空鏈表
if(head == nullptr) return head;
//新建一個節(jié)點next指向head res->next =head
ListNode* res = new ListNode(0,head);
ListNode* cur = res;
while(cur->next != nullptr){
//如果等于則跳過
if(cur->next->val == val){
cur->next = cur->next->next;
}
else{
//如果不等于則繼續(xù)遍歷
cur = cur->next;
}
}
//返回新建節(jié)點的next得到答案
return res->next;
}
};
到了這里,關(guān)于Leetcode刷題筆記題解(C++):203. 移除鏈表元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!