【Leetcode】203. Remove Linked List Elements
删除链表中值为val的节点:

方法1 双指针法

pNode 在前,cur 在后,遇到val跳过,再让pNode的next指向cur

class Solution1(object):
    def removeElements(head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy.next = head
        pNode = dummy
        cur = dummy.next
        while(cur):
            if cur.val == val:
                cur = cur.next
            else:
                pNode.next = cur
                cur = cur.next
                pNode = pNode.next
        pNode.next = cur
        return head

改进下,不需要dummyNode

class Solution1(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        pNode = head
        cur = head.next
        while(cur):
            if cur.val == val:
                cur = cur.next
            else:
                pNode.next = cur
                cur = cur.next
                pNode = pNode.next
        pNode.next = cur
        return head if head.val != val else head.next

方法2

方法1 中跳出循环后都有pNode.next = cur 操作,看beat100%的代码巧妙的避开了这一步骤

class Solution3(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        pNode = head
        cur = head.next
        while(cur):
            if cur.val == val:
            #巧妙之处在于这个地方指定了pNode.next 却不跳转,如果cur.next满足条件才跳转
                pNode.next = cur.next
                cur = cur.next
            else:
            #在此处发生跳转
                pNode = pNode.next
                cur = cur.next
        return head if head.val != val else head.next

方法3 递归法

当前node满足条件则递归处理其next,返回递归处理的next

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

方法4 单指针法

class Solution3(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy.next = head
        cur = dummy
        while(cur.next):
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

相关文章:

  • 2021-12-23
  • 2022-01-04
  • 2021-09-04
  • 2021-07-05
  • 2021-10-04
猜你喜欢
  • 2021-07-02
  • 2021-07-21
  • 2021-10-26
  • 2021-06-11
  • 2022-01-31
  • 2021-09-01
相关资源
相似解决方案