美文网首页
203. Remove Linked List Elements

203. Remove Linked List Elements

作者: April63 | 来源:发表于2018-06-20 11:06 被阅读0次
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def removeElements(self, head, val):
            """
            :type head: ListNode
            :type val: int
            :rtype: ListNode
            """
            if not head:
                return head
            if not head.next:
                if head.val == val:
                    return None
                else:
                    return head
            dummy = ListNode(0)
            dummy.next = head
            pre = dummy
            p = head
            while p:
                if p.val == val:
                    pre.next = p.next
                    p = p.next
                else:
                    pre = p
                    p = p.next
            return dummy.next
    

    有一种很天才的做法,递归法:

    
    class Solution(object):
        def removeElements(self, head, val):
            """
            :type head: ListNode
            :type val: int
            :rtype: ListNode
            """
            if not head:
                return None
            head.next = self.removeElements(head.next, val)
            if head.val == val:
                return head.next
            else:
                return head
        
    
    

    相关文章

      网友评论

          本文标题:203. Remove Linked List Elements

          本文链接:https://www.haomeiwen.com/subject/whityftx.html