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     }
  • 相关阅读:
    JS-排序详解-选择排序
    JS-排序详解-快速排序
    JS-排序详解-冒泡排序
    正则表达式入门
    JS-最全的创建对象的方式
    用JS实现回文数的精准辨别!!!
    基本包装类型
    引用类型之Function类型
    引用类型之Array类型
    Object类型
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418381.html
Copyright © 2011-2022 走看看