栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode203. 移除列表元素,LinkedList

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode203. 移除列表元素,LinkedList

1. 题目描述

题目来源:力扣

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

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

首先,去掉LinkedNode直接的连接(即next关系),重新初始化。再将非val的节点存储到list中,重新生成链表。和reverse链表的思路一致。代码如下,

# 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
        """
        Link_lst = []
        current = head
        # 首先排除特殊情况
        if current is None:
            return current
            # 直接return也可
        # 将非val的ListNode存储起来
        while not current.next is None:
            if current.val != val:
                Link_lst.append(ListNode(current.val))
            current = current.next
        if current.val != val:
            Link_lst.append(current)
        
        # 重新生成LinkedList
        if len(Link_lst)==0:
            return 
        else:
            r = Link_lst[0]
            current = r
            for i in Link_lst[1:]:
                current.next = i
                current = i 
        return r 
        

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890439.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号