我正在InterviewBit上练习链接列表问题。这里的问题是‘给定一个单链表和一个整数K,每次反转列表K的节点,并返回修改后的链表。
注:列表的长度可被K‘整除
按照一种天真的方法,我就是这样做的:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversesubList(self, A, B):
prev = None
cur = A
if cur.next is None:
return A
count = 0
while(cur is not None) and count<B:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
count += 1
self.head = prev
return self.head, cur
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def reverseList(self, A, B):
current = A
last_of_prev = None
count = 0
while current is not None:
reversed_head, new_head = self.reversesubList(current, B)
# print(reversed_head.val)
# print(new_head.val)
if count>0:
last_of_prev.next = reversed_head
else:
start = reversed_head
last_of_prev = current
current.next = new_head
current = new_head
count += 1
return start
这样做的想法是遍历列表,通过切换每次考虑的每组B元素的指针,在一次传递时,我们应该能够完成这个问题。但是,我得到了以下错误,但无法确定原因:
Traceback (most recent call last):
File "main.py", line 228, in <module>
Z = obj.reverseList(A, B)
File "/tmp/judge/solution.py", line 25, in reverseList
reversed_head, new_head = self.reversesubList(current, B)
TypeError: 'ListNode' object is not iterable
任何能让我理解错误的帮助都将不胜感激,谢谢!
发布于 2021-12-30 08:42:53
有以下问题:
reversesubList
有return A
(一个值)和return self.head, cur
(元组)。这是不一致的。在调用此函数时,需要一个元组,因此第一个return
是错误的。实际上,发生这种情况的if
块可以被移除。
return start
的缩进由一个空格(可能只是问题中的一个错误)代替
last_of_prev = current
不仅应该发生在else
的情况下,而且应该总是发生在else
的情况下。所以把它移出else
身体。。
不是问题,而是可以改进以下几点:
count
变量似乎过分了,因为它只用于查看它是否是循环的第一次迭代。为此,您可以使用if last_of_prev
--因此不需要count
变量.reversesubList
不应该分配给self.head
--它永远不会被读取。只需做return prev, nxt
而不做那个作业。current.next = new_head
并不是真正需要的,因为在循环的下一次迭代中,从new_head
开始的(剩余)列表仍然需要反转,因此无论如何都需要更正这个赋值,这将发生在(在下一个迭代中)到last_of_prev.next
.的赋值时。
A
和B
,最好使用更多的描述性变量,比如head
和count
。然后,在reversesubList
函数中,您可以减少给定的count
,而不需要另一个变量。把所有这些结合在一起,我们就会得到这个:
class ListNode:
def __init__(self, x, nxt=None):
self.val = x
self.next = nxt
# Some helper methods to be able to test outside
# the code-challenge site's framework
@classmethod
def of(Cls, values):
head = None
for value in reversed(values):
head = Cls(value, head)
return head
def __iter__(self):
head = self
while head:
yield head.val
head = head.next
class Solution:
def reversesubList(self, head, count):
prev = None
cur = head
while cur is not None and count > 0:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
count -= 1
return prev, cur
def reverseList(self, head, count):
current = head
last_of_prev = None
start = None
while current is not None:
reversed_head, new_head = self.reversesubList(current, count)
if last_of_prev:
last_of_prev.next = reversed_head
else:
start = reversed_head
last_of_prev = current
current = new_head
return start
# Test
lst = ListNode.of([1,2,3,4,5,6,7,8,9])
print(*lst)
lst = Solution().reverseList(lst, 3)
print(*lst)
https://stackoverflow.com/questions/70528635
复制相似问题