自学内容网 自学内容网

leetcode链表(一)-移除链表元素

题目

t. - 力扣(LeetCode)

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

例1

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]


示例 2:

输入:head = [], val = 1
输出:[]


示例 3:

输入:head = [7,7,7,7], val = 7
输出:[]

思路

当需要删除的节点是头节点时,需要单独考虑,这时候设置一个虚拟的头节点,将虚拟的头节点指向真实的头节点,将头节点看作普通节点做同样的操作即可,但最后返回的时候一定要返回虚拟头节点的next。

代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        if not head:
            return
        phead,cur = ListNode(),ListNode()
        phead.next = head
        cur= phead
        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return phead.next


原文地址:https://blog.csdn.net/weixin_40198632/article/details/142829625

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!