在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)
感谢您的评论。我想这个问题的目的是创建一个附加函数来合并两个链表。我想我只是指错了地方。我修改了我的代码如下,它有效:Node类和推送方法有:
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def push(head, data):
n = Node(data)
n.next = head
return n
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.next is not None:
count += 1
cA = cA.next
cA.next = push(cB.next, cB.data)
return headA