Python在单链表merg的输出中缺少值

2024-04-26 23:41:18 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在尝试学习如何合并两个单链表;但是,我似乎不明白为什么在输入值时会丢失第一个值。你知道吗

这是我的班级。。你知道吗

class SinglyListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None

以下是我使用的合并代码:

def mergeList(self, list):
    p = self.head 
    q = list.head
    s = None

    if not p:
        return q
    if not q:
        return p

    if p and q:
        if p.data <= q.data:
            s = p 
            p = s.next
        else:
            s = q
            q = s.next
        new_head = s 

    while p and q:
        if p.data <= q.data:
            s.next = p 
            s = p 
            p = s.next
        else:
            s.next = q
            s = q
            q = s.next
    if not p:
        s.next = q 
    if not q:
        s.next = p 
    return new_head

这些是数组中的数字

  array1 = [ 3, 6, 6, 10, 45, 45, 50] ; 
  array2 = [2, 3, 55, 60 ]

这些是打印代码:

def printList(self):
    temp = self.head
    print "[",
    while temp is not None:
        print temp.data,
        temp = temp.next
    print "]"

s1.mergeList(s2)
print "Content of merged list"
s1.printList()

输出是。。。你知道吗

[ 3 3 6 6 10 45 45 50 55 60 ]

本例中的值2不会被打印出来。 我试着在合并列表中打印新的头的值,得到了2。你知道吗

我不明白的是,为什么当它被打印出来时,列表开头的2的值消失了。你知道吗

谢谢你的帮助。你知道吗


Tags: 代码selfnonedatareturnifinitdef
1条回答
网友
1楼 · 发布于 2024-04-26 23:41:18

将您的代码浓缩到重要部分,我们有:

class SinglyLinkedList:
    #...
    def mergeList(self, list):
        p = self.head 
        q = list.head
        s = None

        #...

        if p and q:
            if p.data <= q.data:
                s = p 
                p = s.next
            else:
                s = q
                q = s.next
            new_head = s

            #...

            return new_head

    #...

    s1.mergeList(s2)
    print "Content of merged list"
    s1.printList()

在合并两个列表时(据我所知,这个函数中的逻辑是正确的),您可以定义一个名为new_head的变量,然后返回它。你知道吗

但是当你调用函数时:

s1.mergeList(s2)

你“抛弃”了返回值。但是这个返回值是合并列表的头,因此如果list[1]的第一个元素小于self的第一个元素,那么打印s1将启动一个元素“late”。你知道吗

相反,考虑一些类似于改变的事情:

return new_head

self.head = new_head

您将看到列表按预期打印。你知道吗

[1]这里可以考虑使用不同的变量名,以避免隐藏内置的list类型。你知道吗

相关问题 更多 >