【发布时间】:2015-11-24 10:47:29
【问题描述】:
我在 python 上将一个链表附加到另一个链表时遇到问题。 我认为逻辑应该是将一个列表的头部指向另一个列表的尾部。我的代码如下。
def append(listA, listB):
if listA == None:
return listB
elif listB == None:
return listA
headA = listA
headB = listB
cA = headA
cB = headB
count = 0
while cA is not None:
count += 1
cA = cA.next
#Here I replace since cA is null, i set it equal to cB
cA = push(cB, cB.data)
return headA
我的测试代码是:
ten = Node(10)
seven = push(ten,7)
six = push(seven,6)
five = push(six,5)
four = push(five,4)
# ten = Node(10)
eleven = Node(11)
three = push(eleven,3)
two = push(three,2)
one = push(two,1)
print_list(one)
print_list(four)
append(one,four)
print_list(one)
【问题讨论】:
-
push和Node是什么?您只是在寻找newList=listA+listB? -
对不起,节点是:class Node(object): def __init__(self, data): self.data = data self.next = None and push is: def push(head, data): n = 节点(数据)n.next = 头部返回 n。 # 我认为你不能为链表做 +。
-
内置的'list'类是双链表,不用自己滚!
-
@AlonsoGutiérrez 将最后一条评论添加到问题中,以便阅读。
-
@EvertW 内置的
list类型不是作为链表实现的,而是作为动态数组实现的。至少在 CPython 中。但是开发人员在某种程度上承诺 O(1) 索引访问,因此在任何可用的 Python 实现中它都不太可能是链表。
标签: python linked-list