小红书笔试题:https://www.nowcoder.com/questionTerminal/a632ec91a4524773b8af8694a51109e7
方法一:
需要自行定义链表结构,将输入的数据保存到你的链表中
class ListNode():
def __init__(self,x):
self.val = x
self.next = None
array = list(map(int,input().split(' ')))
k = int(input())
head = ListNode(-1)
node = head
for i in array:
node.next = ListNode(i)
node = node.next
反转链表后转成字符串输出:
def reverse(head,k):
current = head
cnt = 0
while current and cnt != k:
current = current.next
cnt += 1
if cnt == k:
current = reverse(current,k)
while cnt:
tmp = head.next
head.next = current
current = head
head = tmp
cnt -= 1
head = current
return head
p = reverse(head.next,k)
res = []
while p:
res.append(str(p.val))
p = p.next
print(' '.join(res))
将上面的代码简化一下:
def reverseList_k(head,k):
cur = head
cnt = 0
while cur and cnt != k:
cur = cur.next
cnt += 1
if cnt == k:
cur = reverseList_k(cur,k)
while cnt:
head.next,cur,head = cur,head,head.next
cnt -= 1
head = cur
return head
方法二:
直接用array进行数组元素交换
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))