赞
踩
/** * 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) { ListNode* dummy = new ListNode(0, head); ListNode* cur = head; ListNode* pre = dummy; if(head == nullptr) { return head; } while(cur) { if(cur->val == val) { pre->next = cur->next; delete cur; cur = pre->next; } else { pre = cur; cur = cur->next; } } pre->next = nullptr; return dummy->next; } };
/** * 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) { ListNode* dummy = new ListNode(0, head); ListNode* p = head; ListNode* r = dummy; if(head == nullptr) { return head; } while(p) { if(p->val != val) { r->next = p; r = p; p = p->next; } else { ListNode *q = p; r->next = q->next; delete q; p = r->next; } } r->next = nullptr; return dummy->next; } };
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。