题解 | #每K个一组反转链表#

每K个一组反转链表

https://www.nowcoder.com/practice/a632ec91a4524773b8af8694a51109e7

import sys


class ListNode:
    def __init__(self,value=0,next=None):
        self.value=value
        self.next=next

def parse_input(num):
    if not num:
        return None
    head=ListNode(num[0])
    curr=head

    for value in num[1:]:
        curr.next=ListNode(value)
        curr=curr.next
    return head

def reverse(head,k):
    pre,cur,cnt,tail=None,head,0,head
    while cur and cnt<k:
        cnt+=1
        tmp=cur.next
        cur.next=pre
        pre=cur
        cur=tmp
    return pre,cur,cnt

def reverse_k(head,k):
    if not head:
        return head
    tail=head
    head,next_head,cnt=reverse(head,k)
    if cnt==k:
        next_head=reverse_k(next_head,k)
        tail.next=next_head
    else:
        head,_,_=reverse(head,k)
    return head


num=list(map(int,input().strip().split()))
k=int(input())

head=parse_input(num)
head=reverse_k(head,k)
while head:
    print(head.value,end=' ')
    head=head.next










全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务