leetcode203-Remove Linked List Elements移除链表元素(python)

思路:不用设置两个外部引用,可以每次检查当前节点的下一个节点的值是否等于给定值

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        copy=ListNode(None)
        copy.next=head
        p=copy
        while p.next:
            if p.next.val==val:
                p.next=p.next.next
            else:
                p=p.next
        return copy.next
        

 

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

 

相关文章:

  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
猜你喜欢
  • 2021-07-07
  • 2022-12-23
  • 2021-06-25
  • 2021-07-22
  • 2021-06-15
  • 2022-01-20
  • 2022-02-08
相关资源
相似解决方案