每日一题力扣203

时间:2021-03-16 11:53:35   收藏:0   阅读:0

 

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

 

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        #设置链表头
        current = head
        #如果链表为空,返回空
        if head == None:
            return None
        #当链表头为需要移除的元素时,使链表头指向下一个结点
        while(head):
            if (head.val == val):
                current = head.next
                head = head.next
            else:
                break
        #循环,如果下一个结点的值是需要移除的元素,跳过该结点,指向下一个结点
        while (head and head.next):
            if head.next.val == val:
                head.next = head.next.next
            else:
                head = head.next
        #放回链表头结点
        return current

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!