zoukankan      html  css  js  c++  java
  • 25. 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

    ==================

    思路:

      没有什么坑,就是编码麻烦,

    代码:

    void help_reverseKGroup(ListNode *prev,ListNode *curr,int k){
            ListNode *p = prev->next;
            prev->next = curr->next;
            for(int i = 0;i<k;i++){
                ListNode *tmp = p->next;
                p->next = prev->next;
                prev->next = p;
                p = tmp;
            }
        }
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(k<=1) return head;
            if(head==nullptr || head->next==nullptr)return head;
            ListNode dummy(-1);
            dummy.next = head;
            ListNode *curr,*prev;
            curr = head;
            prev = &dummy;
    
            while(curr){
                int i = 1;
                for(;i<k;i++){
                    if(curr->next)  curr = curr->next;
                    else break;
                }
                if(i!=k) break;
                //showList(dummy.next);cout<<"k1"<<endl;
    
                help_reverseKGroup(prev,curr,k);
    
                //showList(dummy.next);cout<<"k2"<<endl;
                for(i = 0;i<k;i++){
                    prev = curr;
                    curr = curr->next;
                }
                //showList(head);cout<<"k3"<<endl;
            }///while
            return dummy.next;
        }
  • 相关阅读:
    【转】ORACLE日期时间 等函数大全
    list_car()函数小记
    git代码提交流程
    windows连接ubuntu服务器方式
    win10专业版安装docker实战
    selenium来识别数字验证码
    web服务器、WSGI跟Flask(等框架)之间的关系
    pymysql的使用
    sql常用 语句总结
    sql语句insert into where 错误解析
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607600.html
Copyright © 2011-2022 走看看