11.链表区间逆序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou_pp/article/details/86077040

11、链表区间逆序

Description

将单个链表的每K个节点之间逆序,打印出新链表;最后不足K的节点数不需要逆序;要求时间复杂度为O(n),额外空间复杂度为O(1)

Input

输入的每一行的值用空格隔开,第一个表示链表长度,中间为节点值,最后代表K

Output

输出的每一行为新的链表,节点值用空格隔开,末尾不要空格。

Sample Input 1 

8 1 2 3 4 5 6 7 8 3

8 a b c d e f g h 4

Sample Output 1

3 2 1 6 5 4 7 8

d c b a h g f e

import sys
import math
class ListNI:
    def SetK(self,arr):
        m=len(arr)
        for i in range(m):
            s=arr[i][0]
            d=len(arr[i])
            last=int(arr[i][d-1])
            time=math.floor(int(s)/last)
            del arr[i][0]
            del arr[i][d-1-1]
            vg = 0
            vn = 0
            while time>0:
               for j in range(vn,int(last/2)):
                     temp = arr[i][last-j- 1+vg]
                     arr[i][last - j - 1+vg] = arr[i][j+vg]
                     arr[i][j+vg] = temp
               vg=vg+last
               time-=1
            print(" ".join(arr[i]))



if'_main_':
    cldd=ListNI()
    A=[]
    for line in sys.stdin:
        te = line.split()
        A.append(te)
    cldd.SetK(A)

猜你喜欢

转载自blog.csdn.net/zhou_pp/article/details/86077040