4. Python链表

参考文章:

  1. https://stackabuse.com/python-linked-lists/
  2. 04-单链表及结点的定义代码_哔哩哔哩_bilibili
  3. 代码随想录 (programmercarl.com)
  4. 题目参考:203. 移除链表元素

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

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:

        #定义一个虚拟头节点并指向头节点
        dummy_head=ListNode(next=head)
        #定义一个cur指针进行遍历
        cur=dummy_head
        while(cur.next!=None):
            if cur.next.val==val:
                cur.next=cur.next.next#将指针指向下下一个节点
            else:
                cur=cur.next
        return dummy_head.next

你可能感兴趣的:(4. Python链表)