【问题标题】:Append a linked list to the end of another linked list in Python在 Python 中将一个链表附加到另一个链表的末尾
【发布时间】: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)

【问题讨论】:

  • pushNode 是什么?您只是在寻找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


【解决方案1】:

感谢cmets。我想问题的目标是创建一个附加函数来合并两个链表。我想我只是因为指向错误的位置而犯了一个错误。我修改了我的代码如下,它的工作原理: 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2015-07-17
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多