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;
            }
            
        }
    };
    
  • 相关阅读:
    微服务架构编码构建
    Keepalived+Nginx 高可用集群
    Nginx 动静分离
    Nginx 负载均衡
    Nginx 反向代理
    Nginx 常用命令
    React.js |Refs转发
    React.js |错误边界
    做一个简约的博客园皮肤
    React.js |Context的作用与用法
  • 原文地址:https://www.cnblogs.com/superzrx/p/3327633.html
Copyright © 2011-2022 走看看