首页 > 试题广场 >

链表合并

[编程题]链表合并
  • 热度指数:7684 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请编写一段代码,实现两个单向有序链表的合并

输入描述:
第一行一个链表,如1 2 3 4 5

第二行一个链表,如2 3 4 5 6


输出描述:
输出:1 2 2 3 3 4 4 5 5 6
示例1

输入

1 2 3 4 5
2 3 4 5 6

输出

1 2 2 3 3 4 4 5 5 6
def func(lst_one, lst_two):
    len_one = len(lst_one)
    len_two = len(lst_two)
    i = 0
    j = 0
    result_list =[]
    
    while i < len_one and j < len_two:
        if lst_one[i] < lst_two[j]:
            result_list.append(lst_one[i])
            result_list.append(lst_two[j])
        else :
            return result_list
        i += 1
        j += 1
    
    
    for num in result_list:
        print(num, end=" ")
        
lst_one = list(map(int, input().split()))
lst_two = list(map(int, input().split()))
func(lst_one, lst_two)
发表于 2021-07-02 11:00:08 回复(0)
def func(lst_one, lst_two):
    len_one = len(lst_one)
    len_two = len(lst_two)
    i = 0
    j = 0
    result_list =[]
    
    while i < len_one and j < len_two:
        if lst_one[i] <= lst_two[j]:
            result_list.append(lst_one[i])
            i += 1
        else:
            result_list.append(lst_two[j])
            j += 1
    
    while i < len_one:
        result_list.append(lst_one[i])
        i += 1
    
    while j < len_two:
        result_list.append(lst_two[j])
        j += 1
    
    for num in result_list:
        print(num, end=" ")


lst_one = list(map(int, input().split()))
lst_two = list(map(int, input().split()))
func(lst_one, lst_two)

发表于 2019-08-30 23:19:04 回复(0)
n = map(int, raw_input().split())
m = map(int, raw_input().split())
n += m
n.sort()
for i in n :
    print i,
发表于 2019-07-20 07:56:47 回复(2)
""""
列表合并,时间复杂度要求宽松
"""

if __name__ == "__main__":
    a = list(map(int, input().strip().split()))
    b = list(map(int, input().strip().split()))
    ans = sorted(a + b)
    print(' '.join(map(str, ans)))

发表于 2019-07-12 11:02:44 回复(0)
a,b=list(reversed(list(map(int,input().split())))),list(reversed(list(map(int,input().split()))))
print (' '.join([str(a.pop()) if (a and (not b or a[-1]<b[-1])) else str(b.pop()) for _ in range(len(a)+len(b))]))

发表于 2019-06-29 15:09:36 回复(1)