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

    ==================

    思路:

      没有什么坑,就是编码麻烦,

    代码:

    void help_reverseKGroup(ListNode *prev,ListNode *curr,int k){
            ListNode *p = prev->next;
            prev->next = curr->next;
            for(int i = 0;i<k;i++){
                ListNode *tmp = p->next;
                p->next = prev->next;
                prev->next = p;
                p = tmp;
            }
        }
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(k<=1) return head;
            if(head==nullptr || head->next==nullptr)return head;
            ListNode dummy(-1);
            dummy.next = head;
            ListNode *curr,*prev;
            curr = head;
            prev = &dummy;
    
            while(curr){
                int i = 1;
                for(;i<k;i++){
                    if(curr->next)  curr = curr->next;
                    else break;
                }
                if(i!=k) break;
                //showList(dummy.next);cout<<"k1"<<endl;
    
                help_reverseKGroup(prev,curr,k);
    
                //showList(dummy.next);cout<<"k2"<<endl;
                for(i = 0;i<k;i++){
                    prev = curr;
                    curr = curr->next;
                }
                //showList(head);cout<<"k3"<<endl;
            }///while
            return dummy.next;
        }
  • 相关阅读:
    网络之传输层
    局域网的物理组成
    网络基础
    RAID磁盘阵列
    mount挂载和交换分区swap
    Linux文件系统
    sed命令基础2
    sed命令基础
    LVM基础
    磁盘配额基础
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607600.html
Copyright © 2011-2022 走看看