在Python中将一个链表追加到另一个链表末尾

1 投票
1 回答
1173 浏览
提问于 2025-05-10 23:54

我在用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)

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

0

谢谢大家的评论。我想这个问题的目标是创建一个追加函数,用来合并两个链表。我觉得我之前的代码有个错误,是指向了错误的位置。我修改了我的代码,结果现在可以正常工作了:

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

撰写回答