题目
删除链表中等于给定值 val 的所有节点。
示例
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解答
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 31 32 33 34 35 36 37 38 39 40 41 |
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) return NULL; ListNode *cur = head; ListNode *del = NULL; while(cur->next) { if(cur->next->val == val) { del = cur->next; cur->next = del->next; delete del; del = NULL; } else cur = cur->next; } return head->val == val ? head->next : head; } }; // 递归法 class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) return NULL; head->next = removeElements(head->next, val); return head->val == val ? head->next : head; } }; |
评论