203. 移除链表元素

https://leetcode-cn.com/problems/remove-linked-list-elements/https://leetcode-cn.com/problems/remove-linked-list-elements/

解法一:

一次遍历,注意加辅助头结点(考虑删除第一个节点的情况)

# 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:
        Head = ListNode(0)  #辅助头结点
        Head.next = head
        pre, cur = Head, head
        while cur:
            if cur.val == val:  #若要删除,pre不变,修改pre后继
                pre.next = cur.next
            else:  #不删除,pre前移
                pre = cur
            cur = cur.next  #无论如何cur都前移
        return Head.next

最后更新于