203. 移除链表元素

题目描述

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

原题请参考链接https://leetcode-cn.com/problems/remove-linked-list-elements/

题解

方法一 【暴力法】

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        # 如果头节点的值等于val
        while head and head.val == val:
            head = head.next
        # 如果中间节点的值等于val
        cur = head
        while cur and cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

方法二 【虚拟节点】

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        # 如果创建一个虚拟节点,不需要考虑值为val的节点是存在头节点还是中间节点
        dummy_node = ListNode(0)
        tmp.next = head
        cur = dummy_node
        while head:
            if head.val == val:
                cur.next = head.next
                head = head.next
            else:
                cur = cur.next
                head = head.next
        return dummy_node.next
posted @ 2021-02-18 22:36  Bladers  阅读(34)  评论(0)    收藏  举报