#1025 反转链表 (25 分)
代码展示:
headerAddress, N, K = input().split()
N, K = int(N), int(K)
# 映射类型 -> 'address':['data','next','pre']
NodeDict = dict()
for i in range(N):
address, data, next = input().split()
NodeDict[address] = [data, next]
# 遍历链表添加前驱节点指针
datum = list()
pre = '-1'
address = headerAddress
while address!='-1':
data, next = NodeDict[address]
NodeDict[address].append(pre)
pre = address
address = next
# 遍历链表,获得链表有效长度
# print('-'*20)
myLinkedListLenth = 0
address = headerAddress
while address!='-1':
data, next, pre = NodeDict[address]
# print('data={}, next={}, pre={}, address={}'.format(data, next, pre, address))
address = next
myLinkedListLenth += 1
# print('链表长度:',myLinkedListLenth)
# print('#'*20)
# 部分反转
address = headerAddress
startInfo = NodeDict[headerAddress]
pre_temp = '-1'
for i in range(myLinkedListLenth//K):
cnt = 0
while address!='-1' and cnt<K:
if cnt==0:
firstAddr=address # 5
data, next, pre = NodeDict[address]
NodeDict[address] = [data, pre, next]
address = next # 5 9
cnt += 1
address = NodeDict[address][2] # 4 8
NodeDict[address][2] = pre_temp
startInfo[1] = next
startInfo = NodeDict[next] # 5 9
pre_temp = firstAddr # 1 5
address = next # 5
if i==0:
NewheaderAddress = NodeDict[next][2]
NodeDict[firstAddr][1] = next
# 输出所需结果
address = NewheaderAddress
while address!='-1':
data, next, pre = NodeDict[address]
print('{} {} {}'.format(address, data, next))
address = next
测评结果: