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

    链表题,不解释!

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void reverse(ListNode *&head, ListNode *&tail) {
    12         if (tail == NULL) return;
    13         ListNode *pos = head->next, *pre = tail->next, *tmp;
    14         head->next = tail;
    15         head = pos;
    16         while (pos != tail) {
    17             tmp = pos->next;
    18             pos->next = pre;
    19             pre = pos;
    20             pos = tmp;
    21         }
    22         pos->next = pre;
    23         tail = head;
    24     }
    25     
    26     ListNode *reverseKGroup(ListNode *head, int k) {
    27         ListNode *res = new ListNode(-1);
    28         res->next = head;
    29         ListNode *pre = res, *tail = res;
    30         while (tail != NULL) {
    31             for (int i = 0; i < k; ++i) {
    32                 if (tail) tail = tail->next;
    33                 else return res->next;
    34             }
    35             reverse(pre, tail);
    36         }
    37         return res->next;
    38     }
    39 };
  • 相关阅读:
    请简单说一下你了解的端口及对应的服务?
    地址解析协议ARP和逆地址解析协议RARP
    IP地址分类
    OSI分层和五层协议
    对象如何晋升到老年代?
    JVM 垃圾回收机制,何时触发 MinorGC 等操作
    什么是引用?
    类加载机制
    Solaris10怎么创建flash archive
    RPC: program not registered (ZT)
  • 原文地址:https://www.cnblogs.com/easonliu/p/3663083.html
Copyright © 2011-2022 走看看