如何才能正确打印两个升序链表相同的值

问题遇到的现象和发生背景

牛客网算法基础课程链表的题

img

问题相关代码,请勿粘贴截图
n = int(input())
arr1 = [int(i) for i in input().split()]
arr1.reverse()
m = int(input())
arr2 = [int(i) for i in input().split()]
arr2.reverse()
class Node(object):
    def __init__(self, val, next):
        self.val = val
        self.next = next
        
class linkedList(object):
    def __init__(self):
        self.head = None
        self.length = 0
        
    def createLinkedList(self, arr):
        for count in arr:
            self.head = Node(count, self.head)
            self.length += 1
        return self.head, self.length
    
    def printLinkedList(self, linkedlist1, linkedlist2):
        head1 = linkedlist1[0]
        head2 = linkedlist2[0]
        ls = []
        while head1 != None and head2 != None:
            if head1.val < head2.val:
                head1 = head1.next
            elif head1.val > head2.val:
                head2 = head2.next
            else:
                ls.append(head1.val)
                head1 = head1.next
                head2 = head2.next
                if head1 == None or head2 == None:
                    break
        print(*ls)
        
if __name__ == '__main__':
    l = linkedList()
    linkedlist1 = l.createLinkedList(arr1)
    linkedlist2 = l.createLinkedList(arr2)
    l.printLinkedList(linkedlist1, linkedlist2)


运行结果及报错内容

当n<m时,输出为正确答案

img

当n>m时,输出的内容为相同的值加第一个链表中剩余的值

img

我的解答思路和尝试过的方法

始终使第一个列表为短的列表可是使输出正确

n = int(input())
arr1 = [int(i) for i in input().split()]
arr1.reverse()
m = int(input())
arr2 = [int(i) for i in input().split()]
arr2.reverse()
if n > m:
    arr1, arr2 = arr2, arr1
class Node(object):
    def __init__(self, val, next):
        self.val = val
        self.next = next
        
class linkedList(object):
    def __init__(self):
        self.head = None
        self.length = 0
        
    def createLinkedList(self, arr):
        for count in arr:
            self.head = Node(count, self.head)
            self.length += 1
        return self.head, self.length
    
    def printLinkedList(self, linkedlist1, linkedlist2):
        head1 = linkedlist1[0]
        head2 = linkedlist2[0]
        ls = []
        while head1 != None and head2 != None:
            if head1.val < head2.val:
                head1 = head1.next
            elif head1.val > head2.val:
                head2 = head2.next
            else:
                ls.append(head1.val)
                head1 = head1.next
                head2 = head2.next
                if head1 == None or head2 == None:
                    break
        print(*ls)
        
if __name__ == '__main__':
    l = linkedList()
    linkedlist1 = l.createLinkedList(arr1)
    linkedlist2 = l.createLinkedList(arr2)
    l.printLinkedList(linkedlist1, linkedlist2)


输出

img

我想要达到的结果

不通过更改列表顺序,怎样才能使结果始终正确

说明你创建链表的函数有问题,最后一项的next并没有指向none,导致循环不结束,还在打印
其实你break语句都是多余的,只要head1或2有一个是none就应该结束才对
此外,先放到列表里再排序也是多余的,题目已经告诉你了是升序链表,输入的就是升序的数据
打印也应该直接打印,而不是先塞进list里再打印