• 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

    /**
     * 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) 
        {
            if(k<=1 || head==NULL) return head;
            
            
            ListNode* phead=head;
            ListNode* pre=NULL;
          
            ListNode* pl=head;
            ListNode* pr;
            
            while(true)
            {
                //test
                pr=pl;
                for(int i=1;i<k && pr!=NULL;i++) pr=pr->next;
                if(pr==NULL) return phead;
                
                ListNode* pre_next=pl;
                pr=pl->next;
                ListNode* pr_next;
                for(int i=1;i<k;i++)
                {
                    pr_next=pr->next;
                    pr->next=pl;
                    pl=pr;
                    pr=pr_next;
                }
                pre_next->next=pr_next;
                if(pre==NULL)
                    phead=pl;
                else
                    pre->next=pl;
                
                pre=pre_next;
                pl=pr_next;
            }
            return phead;
        }
    }; 
  • 相关阅读:
    Spring AOP详解 、 JDK动态代理、CGLib动态代理
    mysql 日期 字符串 时间戳转换
    图文:通过sql server 连接mysql
    c# 数据绑定之 DataFormatString 格式
    sql 截取字符串与 截取字符串最长的字符串
    oracle 清除表空间
    sql 遍历结果print和表格形式
    国家与城市的sql
    sql2005 将一列的多行内容拼接成一行
    oracle和mssql中复制表的比较
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759296.html
Copyright © 2020-2023  润新知