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     }
  • 相关阅读:
    Ubuntu16.04 + CUDA 8.0 (GTX 1050ti)
    关于MapD的集群建立
    2-7 单位和坐标系
    2-6 光线投射
    2-5 事件系统(Event System)
    2-4 Rect Transform(矩形)组件的属性
    2-3 RectangleTransform矩形组件
    2-2 Graphic Raycasrer组件(光线投射)
    2-1 Ui元素-画布
    1-5 事件方法的执行顺序
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418381.html
Copyright © 2011-2022 走看看