zoukankan      html  css  js  c++  java
  • 25.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.

    If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For example,
    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

    Subscribe to see which companies asked this question

     思路:递归。首先找到第k+1个节点,也就是这一段需要翻转的链表的尾部相连的那个节点。如果找不到第k+1个节点,说明这一段链表长度不足k,无需进行翻转。在找到第k+1个节点的情况下,首先递归求后面直接相连的链表翻转之后的的头结点。然后再将这个头结点之前的需要翻转的链表节点逐个重新连接,进行翻转。最终,返回翻转之后的链表的头结点。

    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode *cur=head;
            int count=0;
            //找到第k+1个节点
            while(cur&&count!=k){
                cur=cur->next;
                count++;
            }
            //找到了第k+1个节点,开始进行翻转
            if(count==k){
                //下一段链表翻转之后的头结点
                cur =reverseKGroup(cur,k);
                while(count-->0){
                    ListNode *temp =head->next;
                    head->next=cur;//将head指向cur
                    cur=head;//将cur向前移动一位
                    head=temp;//将head向后移动一位
                }
                head=cur;//此时,头结点变成原来的尾部节点
            }
            return head;//返回head
        }
    };
  • 相关阅读:
    android ImageSwitcher
    andriod Spinner
    andriod RadioButton
    anriod TabHost
    给大学生的几条良心建议
    6月最新地铁站周边二手房价格出炉
    机器学习 101 Mahout 简介 建立一个推荐引擎 使用 Mahout 实现集群 使用 Mahout 实现内容分类 结束语 下载资源
    Vim设置colorscheme小技巧
    2017年阳光私募基金一季度报告
    实用的 atom 插件
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5281786.html
Copyright © 2011-2022 走看看