每K个一组反转链表

答案来自答主

输入描述:
第一行输入是链表的值第二行输入是K的值,K是大于或等于1的整数输入形式为:1 2 3 4 52
输出描述:
当 k = 2 时,应当输出:2 1 4 3 5当 k = 3 时,应当输出:3 2 1 4 5当k=6时,应当输出:1 2 3 4 5
输入
1 2 3 4 5
2
输出
2 1 4 3 5
确定k有几组,然后用reverse循环翻转每组,
reverse翻转cishu = k//2次,举例3,4时,翻转1,2次,很合理。
链接:https://www.nowcoder.com/questionTerminal/a632ec91a4524773b8af8694a51109e7?f=discussion
#必须3才可以过#raw_input()python2!

def reverse(array, left, right, k):
    cishu = k // 2
    while cishu > 0:
        array[left], array[right] = array[right], array[left]
        left += 1
        right -= 1
        cishu -= 1

array = list(map(int, input().split()))
k = int(input())
beishu = len(array) // k
left = 0
right = k-1
for i in range(beishu):
    reverse(array, left, right, k)
    left += k
    right += k

print(" ".join(str(i) for i in array))

arr = list(map(int,input().split()))
k = int(input())
def reverse(arr,left,right):
    while left<right:
        arr[left],arr[right]=arr[right],arr[left]
        left+=1
        right-=1

group_num = len(arr)//k
left,right = 0,k-1
for i in range(group_num):
    reverse(arr,left,right)
    left+=k
    right+=k


#arr = ' '.join([str(i) for i in arr])
arr = ' '.join(map(str,arr))
print(arr)
#print(k)