Pat乙级1025题——反转链表(Python)一个非零返回,一个运行超时

21 篇文章 0 订阅

注意

  • 注意如果上一次有反转,那么要将上一次最后一个数据的next改成本次反转后的开始的地址
代码测试结果为21分,出现一个非零返回,一个运行超时
#!/usr/bin/python
# -*- coding: UTF-8 -*-

def reverseList():
    input = raw_input().split(' ')
    input[1] = int(input[1])
    input[2] = int(input[2])
    inputList = [] ##存放链表
    global newstart
    for i in range(input[1]):
        inputList.append(raw_input().split(' '))
    def indexFind(item, aimlist): ##根据地址和列表,找到数据在列表中的位置
        for i in range(len(aimlist)):
            if aimlist[i][0] == item:
                return i
    def reverse(start, lastEnd, list): ##根据起始地址,将接下来的input[2]个结点进行反转
        next = start
        address = start
        for i in range(input[2]):
            index = indexFind(next, list)
            next = list[index][2] ##先记住下一个数据的地址
            list[index][2] = address ##把上一个数据的地址赋值给这个数据的next位置,实现反转
            address = list[index][0] ##记住这个数据的地址,用于赋值给下一个数据的next位置
        index = indexFind(start, list) 
        list[index][2] = next
        if lastEnd != 'NULL': ##如果上一次有反转,那么要将上一次最后一个数据的next改成本次反转后的开始的地址
            lastIndex = indexFind(lastEnd, inputList)
            list[lastIndex][2] = address
        lastEnd = list[index][0]
        if start == input[0]:##找到反转后链表开始的位置
            global newstart
            newstart = address
        return next, lastEnd
    start = input[0]
    lastEnd = 'NULL'
    count = input[1]
    while count >= input[2]:
        start, lastEnd = reverse(start, lastEnd, inputList)
        count = count - input[2]
    next = newstart
    for i in range(len(inputList)):
        #print inputList[i]
        index = indexFind(next, inputList)
        print (' ').join(map(str, inputList[index]))
        next = inputList[index][2]
if __name__ == '__main__':
    reverseList()

测试结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值