[LeetCode] 203. Remove Linked List Elements_Easy tag: Linked LIst
2018-08-15 00:38 Johnson_强生仔仔 阅读(153) 评论(0) 编辑 收藏 举报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
基本思路就是直接建一个新的head, 然后每次将非val值的node copy进入新head的tail上面.
比较腻害的做法是用DFS的recursive方法.
Code
1) basic
class Solution: def remLinkedList(self, head, val): ans = dummy = ListNode(1) while head: if head.val != val: dummy.next = ListNode(head.val) dummy = dummy.next head = head.next return ans.next
2) recursive
class Solution: def remLinkedList(self, head, val): if not head :return head.next = self.remLinkedList(head.next, val) return head.next if head.val == val else head