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

    Question

    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

    Solution

    这道题并不难,但是比较繁琐。思路是两步走:

    1. 找出当前要反转的子序列

    2. 反转子序列 (类比反转 m - n 那道题)

    对要反转的子序列,我们用一头(prev)一尾(end)表示

    prev -> 1 -> 2 -> 3 -> 4 -> end

    如k=4,在help函数中,我们定义cur = prev.next, then = cur.next 循环结束条件是then != end。最后返回新序列的尾指针,即下一个要反转序列的prev指针,该例子中为4。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseKGroup(ListNode head, int k) {
    11         if (head == null || k == 0 || k == 1) {
    12             return head;
    13         }
    14         ListNode dummy = new ListNode(-1);
    15         ListNode prev = dummy;
    16         dummy.next = head;
    17         int i = 0;
    18         while (head != null) {
    19             i++;
    20             if (i % k == 0) {
    21                 prev = reverse(prev, head.next);
    22                 head = prev.next;
    23             } else {
    24                 head = head.next;
    25             }
    26         }
    27         return dummy.next;
    28     }
    29     
    30     private ListNode reverse(ListNode prev, ListNode end) {
    31         ListNode cur = prev.next, head = prev.next;
    32         ListNode then = cur.next;
    33         cur.next = null;
    34         ListNode tmp;
    35         while (then != end) {
    36             tmp = then.next;
    37             then.next = cur;
    38             cur = then;
    39             then = tmp;
    40         }
    41         prev.next = cur;
    42         head.next = end;
    43         return head;
    44     }
    45 }
  • 相关阅读:
    Calling Convention的总结
    形参传递关键点
    linux input输入子系统分析《四》:input子系统整体流程全面分析
    22.Linux-块设备驱动之框架详细分析(详解)
    spring: 使用profiles选择数据源(结合嵌入式数据源EmbeddedDatabaseBuilder)
    spring: 使用嵌入式数据源 EmbeddedDatabaseBuilder
    jsp:jstl标签之控制流程
    jsp: jstl标签库
    jsp:tld标签
    spring boot: 组合注解与元注解
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4940982.html
Copyright © 2011-2022 走看看