我被要求反转a以头为参数,其中head是链表,例如:1 – > 2 – >从已经定义的函数返回的3我尝试以这种方式实现函数reverse_linked_list:
def reverse_linked_list(head):
temp = head
head = None
temp1 = temp.next
temp2 = temp1.next
temp1.next = None
temp2.next = temp1
temp1.next = temp
return temp2
pass
class Node(object):
def __init__(self,value=None):
self.value = value
self.next = None
def to_linked_list(plist):
head = None
prev = None
for element in plist:
node = Node(element)
if not head:
head = node
else:
prev.next = node
prev = node
return head
def from_linked_list(head):
result = []
counter = 0
while head and counter < 100: # tests don't use more than 100 nodes, so bail if you loop 100 times.
result.append(head.value)
head = head.next
counter += 1
return result
def check_reversal(input):
head = to_linked_list(input)
result = reverse_linked_list(head)
assert list(reversed(input)) == from_linked_list(result)
它以这种方式调用:check_reversal([1,2,3]).我为反转列表而编写的函数给出了[3,2,1,2,1,2,1,2,1],仅适用于长度为3的列表.如何将其推广为长度列表N +