链表以k个一组进行翻转(2014美团研发笔试)

给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6。

ListNode *reverseKGroup(ListNode *head, int k)
{
    if (head == nullptr || head->next == nullptr || k < 2)
        return head;
    ListNode *next_group = head;
    for (int i = 0; i < k; ++i)
    {
        if (next_group)
            next_group = next_group->next;
        else
            return head;
    }
// next_group is the head of next group
// new_next_group is the new head of next group after reversion
    ListNode *new_next_group = reverseKGroup(next_group, k);
    ListNode *prev = NULL, *cur = head;
    while (cur != next_group)
    {
        ListNode *next = cur->next;
        cur->next = prev ? prev : new_next_group;
        prev = cur;
        cur = next;
    }
    return prev; // prev will be the new head of this group
}

若末尾不足K的也进行翻转,则如下

/* Reverses the linked list in groups of size k and returns the
   pointer to the new head node. */
struct node *reverse (struct node *head, int k)
{
    struct node* current = head;
    struct node* next;
    struct node* prev = NULL;
    int count = 0;

    /*reverse first k nodes of the linked list */
    while (current != NULL && count < k)
    {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
        count++;
    }

    /* next is now a pointer to (k+1)th node
       Recursively call for the list starting from current.
       And make rest of the list as next of first node */
    if(next !=  NULL)
    {
        head->next = reverse(next, k);
    }

    /* prev is new head of the input list */
    return prev;
}

见Geeks、Leetcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值