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

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode reverseKGroup(ListNode head, int k) {
    14         if(head == null || k == 1){
    15             return head;
    16         }
    17         
    18         int len = 0;
    19         ListNode p = head;
    20         while(p != null){
    21             p= p.next;
    22             len++;
    23         }
    24         
    25         
    26         ListNode safe = new ListNode(-1);
    27         safe.next = head;
    28         
    29         ListNode pre = safe, cur = head, post = head.next;
    30         
    31         //记录需要翻转几次
    32         int m = len/k;
    33         
    34         for(int i = 0; i < m; i++){
    35             //跳出 while 之后的新循环开始前 cur 和 post指向同一个Node
    36             post = cur.next;
    37             
    38             // 记录翻转了几个Node了
    39             int j = 0;
    40             while(post != null){
    41                 ListNode tmp = post.next;
    42                 post.next = cur;
    43                 cur = post;
    44                 post = tmp;
    45                 j++;
    46                 if(j == k-1){
    47                     break;
    48                 }
    49             }
    50             
    51             ListNode tmp = pre.next;
    52             pre.next = cur;
    53             tmp.next = post;
    54             pre = tmp;
    55             cur = pre.next;
    56         }
    57         
    58         return safe.next;
    59     }
    60     
    61 }
    View Code
  • 相关阅读:
    【重构学习】12 重构学习感想
    【重构学习】11 大型重构
    【重构学习】10 继承关系的重构
    【重构学习】09 函数调用的重构
    【重构学习】08 条件表达式的重构
    嵊州D4T1 翻车 rollover 真的翻车了
    计算圆内格点数
    嵊州D3T2 福尔贝斯太太的快乐夏日 summer
    嵊州D3T3 light
    嵊州D3T1 山魔 烙饼问题
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3538143.html
Copyright © 2011-2022 走看看