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

    思路:

    类似Reverse Linked List II

    代码:

     1     ListNode *reverseKGroup(ListNode *head, int k) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         if(head == NULL || k <= 1)
     5             return head;
     6         ListNode *pre, *begin, *end, *post, *tmp, *result = NULL, *last, *nextp;
     7         int n;
     8         pre = NULL;
     9         tmp = head;
    10         while(tmp){
    11             n = 0;
    12             begin = tmp;
    13             while(tmp){
    14                 n++;
    15                 if(n == k)
    16                     break;
    17                 tmp = tmp->next;
    18             }
    19             if(tmp == NULL)
    20                 break;
    21             end = tmp;
    22             post = end->next;
    23             if(pre == NULL)
    24                 result = end;
    25             else
    26                 pre->next = end;
    27             last = begin;
    28             tmp = begin->next;
    29             while(tmp != post){
    30                 nextp = tmp->next;
    31                 tmp->next = last;
    32                 last = tmp;
    33                 tmp = nextp;
    34             }
    35             begin->next = post;
    36             tmp = post;
    37             pre = begin;
    38         }
    39         if(result)
    40             return result;
    41         return head;
    42     }
  • 相关阅读:
    Java内存区域
    spring学习之Bean
    记一次日本公司的Java面试
    java中打印输出数组内容的三种方式
    Java创建子类时构造器执行顺序
    转发&重定向
    Java继承
    GXOI&GZOI
    LCT能干啥???
    后缀自动机的一些应用
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418381.html
Copyright © 2011-2022 走看看