leetcode之Remove Linked List Elements

本文探讨了一种优化的链表元素移除算法实现方式,通过将链表转换为列表,删除指定元素后再转回链表,提高了算法效率。同时,提供了一个简化版的实现方法,减少了内存使用和提高了运行速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题我采用了另一个思路,转化为list,然后删除元素之后再按照list转回来。代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        b = []
        if head == None:
            return None
        while head != None:
            b.append(head.val)
            head = head.next
        for i in range(len(b))[::-1]:
            if b[i] == val:
                del b[i]
        print b
        c = ListNode(0)
        a = c
        for i in b:
            a.next = ListNode(i)
            a = a.next
        return c.next

时间上耗费倒是挺多的,先尝试一下.

从另外一道题上得到了启发,于是修改了一下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        c = head
        if c == None:
            return None
        while c!= None:
            if c.next != None:
                if c.val == val:
                    c.val = c.next.val
                    c.next = c.next.next
                else:
                    c = c.next
            else:
                if c.val != val:
                    break
                else:
                    slow = head
                    fast = head
                    if slow.next == None:
                        return None
                    slow = slow.next
                    while slow.next != None:
                        slow = slow.next
                        fast = fast.next
                    fast.next = fast.next.next
                    break
                    
        return head

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值