这题我采用了另一个思路,转化为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
本文探讨了一种优化的链表元素移除算法实现方式,通过将链表转换为列表,删除指定元素后再转回链表,提高了算法效率。同时,提供了一个简化版的实现方法,减少了内存使用和提高了运行速度。
1324

被折叠的 条评论
为什么被折叠?



