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

  • 注意如果上一次有反转,那么要将上一次最后一个数据的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()

猜你喜欢

转载自blog.csdn.net/coder_wu/article/details/82318900