LeetCode 202. 移除链表元素 (Remove Linked List Elements)[简单]

lework · 2020年04月28日 · 最后由 lework 回复于 2020年04月28日 · 121 次阅读

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
# 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:
        node = ListNode(val+1)
        node.next = head
        pre, cur = node, head
        while cur:
            if cur.val == val:
                pre.next = cur.next
                cur = cur.next
            else:
                pre = cur
                cur = cur.next
        return node.next
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册