码迷,mamicode.com
首页 > 其他好文 > 详细

25. Reverse Nodes in k-Group

时间:2018-08-09 19:32:44      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:ati   ret   node   solution   eve   color   turn   its   k-group   

25. Reverse Nodes in k-Group



      
      

class Solution {
    public ListNode reverseList(ListNode head) {
      if(head == null || head.next == null){
        return head;    
      }
      
      ListNode p = reverseList(head.next);
      head.next.next = head;
      head.next = null;
      return p;
    }
}


class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
      //1. test weather we have more then k node left, if less then k node left we just return head
      ListNode node = head;
      int count = 0;
      while(count < k ){
        if(node == null){
          return head;
        }
        node = node.next;
        count++;
      }
      // 2.reverse k node at current level (= reverse list iteratively )
      ListNode prev = reverseKGroup(node, k); //prev node point to the the answer of sub-problem 
      while (count > 0){
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
        count = count - 1;
      }
      return prev; 
    }
}
     
      
// 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 
// 3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 7 -> 8

// prev the head after reverse of every subproblem, 
// so prev is 3, prev is 6, prev is 7 (when there is not enough , return itself , which is head , which is 7 
// 这道题很考察recursion,这个题和基本的 reverse linked list recursively 的结构很像, 但是做法上不同, 但是结构上可以学一下, 都是先解决 subproblem, 拿到subproblem 的解之后, 在做当前的事。 注意这个return 值很关键,  

// 实际的reverse每个subproblem 是 和 基本的reverse linked list iteratively 基本一样。 
// 这个一会自己写, 像面试一样    

 

25. Reverse Nodes in k-Group

标签:ati   ret   node   solution   eve   color   turn   its   k-group   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!