zoukankan      html  css  js  c++  java
  • LeetCode-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:
    
        void reverseK(ListNode *head, int k,ListNode** start,ListNode** end){
            
            if(head==NULL){
                *start=NULL;
                *end=NULL;
            }
            else{
                ListNode* temp2;
                ListNode* temp;
                ListNode* ptr;
                int count=0;
                ptr=head;
                while(ptr!=NULL){
                    count++;
                    if(count==k)break;
                    ptr=ptr->next;
                }
                if(count<k){
                    *start=head;
                    *end=NULL;
                }
                else{
                    *start=ptr;
                    *end=head;
                    ptr=head;
                    temp=ptr->next;
                    ptr->next=(*start)->next;
                    for(int i=1;i<k-1;i++){
                        temp2=temp->next;
                        temp->next=ptr;
                        ptr=temp;
                        temp=temp2;
                    }
                    (*start)->next=ptr;
    				head=*start;
                }
            }
        }
        ListNode *reverseKGroup(ListNode *head, int k) {
             // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(head==NULL)return NULL;
            else{
                if(k<2)return head;
                ListNode* start;
                ListNode* end;
    			ListNode* lend;
                ListNode* ret;
                reverseK(head,k,&ret,&end);
                lend=end;
    			while(lend!=NULL){
                    reverseK(lend->next,k,&start,&end);
    				lend->next=start;
    				lend=end;
    			}
               return ret;
            }
            
        }
    };
    
  • 相关阅读:
    JSP—简介
    Dream
    树状数组模板
    夜未央Test1题解
    夜未央Test1
    并查集模板
    给即将面临Noip的二班同学
    USACO chapter1
    二叉堆模板
    线段树模板
  • 原文地址:https://www.cnblogs.com/superzrx/p/3327633.html
Copyright © 2011-2022 走看看