25. Reverse Nodes in 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 基本一样。 
// 这个一会自己写, 像面试一样    

 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed.

 
 

posted on 2018-08-09 18:20  猪猪&#128055;  阅读(99)  评论(0)    收藏  举报

导航