问题遇到的现象和发生背景
牛客网算法基础课程链表的题
问题相关代码,请勿粘贴截图
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时,输出为正确答案
当n>m时,输出的内容为相同的值加第一个链表中剩余的值
我的解答思路和尝试过的方法
始终使第一个列表为短的列表可是使输出正确
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)
输出
我想要达到的结果
不通过更改列表顺序,怎样才能使结果始终正确