AcWing 1626. 链表元素分类
原题链接
简单
作者:
aac
,
2024-11-25 18:16:09
,
所有人可见
,
阅读 1
# 我嫌每次输出都要写05d麻烦,直接用字典存了
e = {};ne = {}
h,n,k = input().split()
k = int(k)
for i in range(int(n)):
addr,data,next = input().split()
e[addr] = int(data)
ne[addr] = next
"""
因为题干说明了每一类内部元素的顺序是不能改变的,将该链表划分为三个部分
遍历该链表的每一个元素,分别和0和k比较,将其划分到相应的part
"""
part1 = []
part2 = []
part3 = []
i = h
while i != "-1":
val = e[i]
if val < 0:
part1.append([i,e[i]])
elif val >= 0 and val <= k:
part2.append([i,e[i]])
else:
part3.append([i,e[i]])
i = ne[i]
parts = [part1,part2,part3]
ans = []
for part in parts: # 将三个部分合并
for x in part:
ans.append(x)
for i in range(len(ans)):
if i == len(ans) - 1:
print(ans[i][0],ans[i][1],-1)
else:
print(ans[i][0],ans[i][1],ans[i + 1][0])