【发布时间】:2014-02-27 01:22:19
【问题描述】:
我被要求反转以 head 作为参数的 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
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 的列表?
【问题讨论】:
-
我没见过python中链表的实际用法,太低级了。这是一个很好的解释,为什么你不会使用它。 stackoverflow.com/questions/280243/python-linked-list#280284
-
好吧,这可能不太好,但 OP 被 要求 去做(家庭作业?):P
-
@Ramya 答案取决于你想怎么做。我们不知道您是否可以在
reverse_linked_list中使用 Python 列表。如果是后者,那么我们需要知道您正在使用的listutils... -
@Ricardo cardenes我不能使用列表,但是,我的 listutils 函数将列表 ex:[1,2,3] 转换为链表。所以我应该将尾节点作为头节点
-
@Ramya 我的意思是:如果您使用我们不知道的库,我们无法帮助您。我们可以编写伪代码向您展示如何操作,但这在 Internet 和教科书中随处可见,如果这是家庭作业(并且看起来 100% 喜欢它),您应该至少展示一段代码,您首先尝试这样做,然后我们可能会更正它 - 作为一般规则,这就是您应该在 StackOverflow 中提问的方式。
标签: python linked-list