203 移除链表元素
本文最后更新于:2022年8月27日 晚上
删除链表中等于给定值 val 的所有节点。
示例:
| 输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) return head; ListNode* dummyHead = new ListNode(-1, head); ListNode* cur = dummyHead; while(cur->next){ if(cur->next->val==val){ ListNode* delNode = cur->next; cur->next = delNode->next; delete delNode; }else{ cur = cur->next; } } return dummyHead->next; } };
|
| class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head==nullptr){ return head; } head->next = removeElements(head->next, val); return head->val == val ? head->next : head; } };
|
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null) { return head; } ListNode dummyHead = new ListNode(-1, head); ListNode cur = dummyHead; while (cur.next != null) { if (cur.next.val == val) { cur.next = cur.next.next; } else { cur = cur.next; } } return dummyHead.next; } }
|
迭代法
| class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null) { return head; } head.next = removeElements(head.next, val); return head.val == val ? head.next : head; } }
|