• 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;
            }
            
        }
    };
    
  • 相关阅读:
    curl 空格和转义符
    supervisor
    pandas 小笔记
    bert 进行文本相似度计算
    认股权证的会计处理
    企业所得税汇算清缴
    调整事项与非调整事项的区别
    centos 挂载windows 2003 smb
    如何获得带转义的json内容
    安装了vs2019 编译node-sass node-gyp 找不到编译器的解决方法
  • 原文地址:https://www.cnblogs.com/superzrx/p/3327633.html
Copyright © 2020-2023  润新知