zoukankan      html  css  js  c++  java
  • LeetCode-Reverse Nodes in k-Group

    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.

    源码:

     1 #include <iostream>
     2 using namespace std;
     3 
     4 ListNode *reverse(ListNode *head,ListNode *last_tail){ 
     5       ListNode *next_node=head->next;
     6       ListNode *res=head;
     7       
     8       while(next_node){
     9             ListNode *tmp=next_node->next;
    10             next_node->next=head;
    11             head=next_node;
    12             next_node=tmp;
    13       }
    14       
    15       last_tail->next=head;
    16       return res;
    17 }
    18 
    19 ListNode* reversekGroup(ListNode *head,int k){
    20      ListNode *newHead=new ListNode(0);
    21      newHead->next=head;
    22      
    23      int cnt=0;
    24      ListNode *cur_node=head;
    25      ListNode *last_tail=newHead;
    26      while(cur_node){
    27            cnt++;
    28            if(cnt==k){
    29                 ListNode *tmp=cur_node->next;
    30                 cur_node->next=0;
    31                 
    32                 last_tail=reverse(last_tail->next,last_tail);
    33                 last_tail->next=tmp;
    34                 
    35                 cnt=0;
    36                 continue;
    37            }
    38            cur_node=cur_node->next;
    39      }
    40      return newHead->next;
    41 }

     

  • 相关阅读:
    C语言II博客作业03
    C语言II博客作业02
    C语言II博客作业01
    学期总结
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言|博客作业05
    C语言I博客作业04
    【lhyaaa】2020深圳大湾区比赛总结
  • 原文地址:https://www.cnblogs.com/sixue/p/4014594.html
Copyright © 2011-2022 走看看