码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-15 01:19:44      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:asi   def   tag   sel   rom   tput   solution   inpu   not   

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

标签:asi   def   tag   sel   rom   tput   solution   inpu   not   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9479074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!