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 }
  • 相关阅读:
    Hibernate多对一ManytoOne
    eclipse中配置MAVEN并使用阿里云代理
    火车采集器 帝国CMS7.2免登录发布模块
    JavaScript数据类型
    JavaScript 命名规则
    帝国cms 无法生成静态页
    帝国cms 页面统计
    PHP类型转换
    Excel小写金额转大写金额公式
    新时期大站协议脚本邮件群发软件 怎么样
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4940982.html
Copyright © 2011-2022 走看看