203. 移除链表元素

2019-05-20  本文已影响0人  好吃红薯

删除链表中等于给定值 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:
        empty_head = ListNode(-1)
        empty_head.next = head
        cur = empty_head
        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return empty_head.next
上一篇 下一篇

猜你喜欢

热点阅读