我正在面试比特上练习链表问题。这里的问题是'给定一个单链表和一个整数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
任何能让我理解错误的帮助都将不胜感激,谢谢!
存在以下问题:
-
reversesubList
同时具有return A
(一个值(和return self.head, cur
(元组(。这是不一致的。在调用此函数时,需要一个元组,因此第一个return
是错误的。实际上,if
块发生的地方,可以直接删除 -
return start
的缩进偏离了一个空格(可能只是问题中的拼写错误( -
分配
last_of_prev = current
不仅应该发生在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)