PAT 乙级(Python) #1025 反转链表 (25 分)

#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

测评结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值