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;
            }
            
        }
    };
    
  • 相关阅读:
    16进制字符串的转换
    UINavigationBar统一修改导航条样式
    3D touch
    WKWebView
    CAEmitterLayer 粒子效果(发射器)
    SDWebImage下载图片的使用
    PHP之string之str_shuffle()函数使用
    Redis之hiredis API (String)
    Redis之数据类型Sting字符串
    PHP之string之str_repeat()函数使用
  • 原文地址:https://www.cnblogs.com/superzrx/p/3327633.html
Copyright © 2011-2022 走看看