zoukankan      html  css  js  c++  java
  • 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;
        }
    }; 
  • 相关阅读:
    Stm32高级定时器(一)
    AES算法简介
    vsim仿真VHDL输出fsdb格式文件
    ncsim仿真VHDL
    云贵高原骑行
    触发器(笔记)
    几种常见的十进制代码(笔记)
    时序电路分类
    组合逻辑电路和时序逻辑电路比较
    数字电路基础(网络整理)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759296.html
Copyright © 2011-2022 走看看