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;
            }
            
        }
    };
    
  • 相关阅读:
    解释一下,@SpringBootApplication
    mybatis的一堆多映射使用配置
    SSM基础pom和xml的整合配置
    获取form表单所有数据最快方式
    两个大神的配置
    springmvc 注解详解
    自适应组件导航栏
    文本相似度的衡量之余弦相似度
    Pandas系列(十四)- 实战案例
    selenium常用操作
  • 原文地址:https://www.cnblogs.com/superzrx/p/3327633.html
Copyright © 2011-2022 走看看