移除链表元素python3(leetcode203)

#203. 移除链表元素​​​​​​

#leetcode203

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

需要注意的是head节点的处理,如果head的值等于目标值,则head需要删除,但是head删除后指针找不到指向下一个节点的地址了,所以设置虚拟head,最终return的是虚拟head的next才是真正的头节点

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy_head = ListNode(-1)
        dummy_head.next = head
        cur = dummy_head #需要cur进行移动判断条件,cur最终回不到头节点,链表是单向的,cur最终会移动到null

        while(cur.next != None): #判断是否为空ListNode
            if(cur.next.val == val): #下一个节点的值与val相等时
                cur.next = cur.next.next #删除下一个节点,直接指向下下个节点
            else:
                cur = cur.next #将指针移动到下一个节点上继续判断
        return dummy_head.next #dummy_head不是头节点,.next才是头节点

 

Guess you like

Origin blog.csdn.net/ziqingnian/article/details/121858138