Problem 2.2: Reverse (100 pts)
Problem
Write a function
reversewhich takes in a linked listlnk, reverses the order of it and returns the reversed list(i.e. return a new reference to the head of the reversed list).There is more than one way to solve this problem. Can you come up with more solutions?
编写一个函数 reverse,它接受一个链表 lnk,反转其顺序并返回反转后的链表(即返回指向反转后链表头部的引用)。
解决这个问题的方法不止一种。你能想出更多的解决方案吗?
def reverse(lnk):
""" Reverse a linked list.
>>> a = Link(1, Link(2, Link(3)))
>>> # Disallow the use of making new Links before calling reverse
>>> Link.__init__, hold = lambda *args: print("Do not steal chicken!"), Link.__init__
>>> try:
... r = reverse(a)
... finally:
... Link.__init__ = hold
>>> print(r)
<3 2 1>
>>> a.first # Make sure you do not change first
1
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: Your implementation should mutate the original linked list. DO NOT create any new linked lists.
Hint2: By
reversewe mean therestattribute of eachLinkobject should be modified. If you simply exchange thefirstattribute of eachLinkobject, it is not considered asreverse.Hint3: It is guaranteed that the linked list is acyclic.
-
你的实现应该修改原始链表。不要创建任何新的链表。
-
我们所说的
reverse是指每个Link对象的rest属性应该被修改。 如果你只是交换每个Link对象的first属性,这不被认为是reverse。 -
保证链表是无环的。