【2021/6/5 刷题笔记】移除链表元素


移除链表元素

【题目】

给你一个链表的头节点 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
  • 输出:[]

提示:

  • 列表中的节点在范围 [0, 104] 内
  • 1 <= Node.val <= 50
  • 0 <= k <= 50

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

【我的方法1】

通过pre指针以及cur指针完成链表节点的删除。

# 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: ListNode, val: int) -> ListNode:
        while(head!=None and head.val==val):
            head=head.next
        pre=ListNode()
        pre.next=head
        cur=head
        while(cur!=None):
            if cur.val==val:
                pre.next=cur.next
                cur=pre.next
            else:
                cur=cur.next
                pre=pre.next
        return head
# 执行用时:96 ms, 在所有 Python3 提交中击败了5.07%的用户
# 内存消耗:17.9 MB, 在所有 Python3 提交中击败了18.86%的用户

【我的方法2】

新建一个链表,把非val的节点都复制过去。(空间换时间)

# 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: ListNode, val: int) -> ListNode:
        # while(head!=None and head.val==val):
        #     head=head.next
        res=ListNode()
        cur=res
        while(head):  # 非空
            if head.val!=val:
                temp=ListNode(head.val)
                cur.next=temp
                cur=cur.next
            head=head.next
        return res.next  # 注意返回的没有头节点
# 执行用时:72 ms, 在所有 Python3 提交中击败了63.97%的用户
# 内存消耗:19.4 MB, 在所有 Python3 提交中击败了5.87%的用户
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值