1079: 合并链表
内存限制:128 MB
时间限制:1.000 S
评测方式:文本比较
命题人:
提交:91
解决:40
题目描述
给定两个按照升序排序的链表lista和listb及对应的头指针ahead和bhead,现在要将两个链表进行合并,合并后依旧保持升序
保证两个链表中所有节点无重复元素
输出合并后的链表的逻辑结构和物理结构
完善merge()函数以解决问题
输入
第一行为lista的头指针ahead
第二行为listb的头指针bhead
第三行为节点数n
接下来n行代表节点的数据域和指针域,用空格隔开
输出
第一行为链表的逻辑结构,按逻辑顺序输出每个节点的数据域,每个数据使用"->"隔开,可以使用上一题中完成的函数来输出
接下来n行:每行输出一个节点,包含数据域和指针域,使用一个空格隔开
样例输入 复制
0
1
4
10 -1
1 2
2 3
3 -1
样例输出 复制
1->2->3->10
10 -1
1 2
2 3
3 0
提示
def output(a, head):
result = ""
p = head
while a[p][1] != -1:
result += str(a[p][0]) + "->"
p = a[p][1]
result += str(a[p][0])
return result
def merge(a, ahead, bhead):
return ahead
# 读取输入
ahead = int(input())
bhead = int(input())
n = int(input())
a = []
for i in range(n):
node_data, node_pos = map(int, input().split())
a.append([node_data, node_pos])
# 合并链表
head = merge(a, ahead, bhead)
print(output(a, head))
# 输出链表
for node in a:
print(node[0], node[1])
result = ""
p = head
while a[p][1] != -1:
result += str(a[p][0]) + "->"
p = a[p][1]
result += str(a[p][0])
return result
def merge(a, ahead, bhead):
return ahead
# 读取输入
ahead = int(input())
bhead = int(input())
n = int(input())
a = []
for i in range(n):
node_data, node_pos = map(int, input().split())
a.append([node_data, node_pos])
# 合并链表
head = merge(a, ahead, bhead)
print(output(a, head))
# 输出链表
for node in a:
print(node[0], node[1])