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

     1 public class Solution {
     2     public ListNode reverseKGroup(ListNode head, int k) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         
     6         if(head == null || k == 1)
     7             return head;
     8             
     9         int len = 0;
    10         ListNode p = head;
    11         while(p != null){
    12             p = p.next;
    13             len ++;
    14         }
    15         
    16         ListNode safeG = new ListNode(-1);
    17         safeG.next = head;
    18         ListNode pre = safeG, cur = head, post = head.next;
    19         
    20         int m = len / k;
    21         for(int i = 0; i < m; i++){
    22             post = cur.next;
    23             //reverse(pre, cur, post, k);
    24             int j = 0;            
    25             while(post != null){
    26                 ListNode tmp = post.next;
    27                 post.next = cur;
    28                 cur = post;
    29                 post = tmp;
    30                 j ++;
    31                 if(j == k - 1)
    32                     break;
    33             }
    34             ListNode tmp = pre.next;
    35             pre.next = cur;
    36             tmp.next = post;
    37             pre = tmp;
    38             cur = pre.next;
    39             
    40         }
    41         
    42         return safeG.next;
    43         
    44     }
    45     
    46     public void reverse(ListNode pre, ListNode cur, ListNode post, int k){
    47         int i = 0;            
    48         while(post != null){
    49             ListNode tmp = post.next;
    50             post.next = cur;
    51             cur = post;
    52             post = tmp;
    53             i ++;
    54             if(i == k - 1)
    55                 break;
    56         }
    57     }
    58 }
  • 相关阅读:
    @font-face
    闭包
    DOM事件
    DOM属性
    使用谷歌chrome浏览器查看任何标签的固有属性
    chmod命令
    C++笔记之零碎点
    C++学习之 —— 输入输出
    常见素数筛选方法原理和Python实现
    Django的MVT模型
  • 原文地址:https://www.cnblogs.com/jasonC/p/3431755.html
Copyright © 2011-2022 走看看