[LeetCode] 203. Remove Linked List Elements_Easy tag: Linked LIst

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 203. Remove Linked List Elements_Easy tag: Linked LIst相关的知识,希望对你有一定的参考价值。

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

 

以上是关于[LeetCode] 203. Remove Linked List Elements_Easy tag: Linked LIst的主要内容,如果未能解决你的问题,请参考以下文章

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

LeetCode 203. Remove Linked List Elements

LeetCode 203 Remove Linked List Elements