#Leetcode# 203. Remove Linked List Elements
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 203. Remove Linked List Elements相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/remove-linked-list-elements/
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
递归代码:
/** * 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; head -> next = removeElements(head -> next, val); return head -> val == val ? head -> next : head; } };
非递归代码:
/** * 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) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy -> next = head; while(pre -> next) { if(pre -> next -> val == val) { ListNode *t = pre -> next; pre -> next = t -> next; t -> next = NULL; delete t; } else pre = pre -> next; } return dummy -> next; } };
被链表支配的上午
以上是关于#Leetcode# 203. Remove Linked List Elements的主要内容,如果未能解决你的问题,请参考以下文章
Java [Leetcode 203]Remove Linked List Elements
leetcode?python 203. Remove Linked List Elements
203. Remove Linked List Elements - LeetCode
LeetCode OJ 203Remove Linked List Elements