Reverse Nodes in k-Group

  • 问题介绍
    • 问题描述:
      • Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
      • k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
    • 示例:
      • Given this linked list: 1->2->3->4->5
        • For k = 2, you should return: 2->1->4->3->5
        • For k = 3, you should return: 3->2->1->4->5
    • 条件限制:
      • Only constant extra memory is allowed.
      • You may not alter the values in the list’s nodes, only nodes itself may be changed.
  • 解决思路
    • 思路:分析题意后,将题目分为两个需要解决的问题:
      1. 对于一个链表将其翻转;
        * 对于需要进行翻转的操作,需要对给定的链表新建一个头指针,防止链表在转换的时候丢失;同时给定两个需要转化链表的指针:一个起始节点的前一个节点pre_head指针、另一个结束节点指针end;此外设立一个cur指针指向当前需要处理的节点,cur每次都等于pre_head指针指向的下一个位置,每次将cur指针指向的节点放到end指针指向节点的后面,直到cur指向的节点等于end指向的节点,此时pre_head指向转换后的链表,同时返回一个last指针指向转换后的最后一个节点,此时last可以作为下一轮转化的pre_head,示意图如下(对1->2->3->4进行翻转);
        * 节点翻转过程示意图
      2. 将链表按k个节点一组进行分组;
        * 对题目给定的链表进行遍历,pre_head为链表新加的头指针或翻转函数返回的last,每次遍历k个节点后end为当前遍历到的节点,然后进行翻转操作;当遍历链表结束,但计数器没有满k的时候返回pre_head即为最后所求的链表;
  • 代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* e=head;       
        ListNode* resp=new ListNode(-1);
        (*resp).next=head;
        ListNode* pre_head=resp;
        int sign=0;
        if(k==1||head==NULL)
        {
            return head;
        }
       
        while(e!=NULL)
        {
            for(int i=1;i<k;i++)
            {
                e=(*e).next;
                if(e==NULL&&i<=k-1)
                {
                    sign=1;   
                    break;
                }
            }
            if(sign==1)
            {
                break;
            }
            else
            {
                pre_head=Proc(pre_head,e);
                e=(*pre_head).next;
            }
        }
        return (*resp).next;
    }
    ListNode* Proc(ListNode* pre_head,ListNode* end)
    {
        ListNode* cur=(*pre_head).next;
        ListNode* last=(*pre_head).next;
        while(cur!=end)
        {
            (*pre_head).next=(*cur).next;
            (*cur).next=(*end).next;
            (*end).next=cur;
            cur=(*pre_head).next;
        }
        return last;
    }
};
Created with Raphaël 2.2.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值