25. Reverse Nodes in k-Group (JAVA)

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 kthen 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.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k == 1) return head;
        
        ListNode cur = head;
        ListNode curHead = head; //head of current subgroup
        ListNode nextHead = head; //head of next subgroup
        ListNode preTail = null; //tail of previous subgroup
        while(true){
            //check whether there's enough elements in subgroup
            for(int i = 1; i < k; i++){
                if(cur == null) break; //not enough element in subgroup
                cur = cur.next;
            }
            if(cur == null) break; //not enough element in subgroup
            
            //reverse nodes
            cur = curHead.next;
            for(int i = 1; i < k; i++){
                nextHead = cur.next;
                if(preTail==null) {
                    cur.next = head;
                    head = cur;
                }
                else {
                    cur.next = preTail.next;
                    preTail.next = cur;
                }
                cur = nextHead;
            }
            curHead.next = nextHead;
            preTail = curHead;
            curHead = nextHead;
            
        }
        return head;
    }
}

因为while语句是无条件循环,特别要注意k==1时的死循环。

 

posted on 2019-04-26 18:29  joannae  阅读(112)  评论(0编辑  收藏  举报

导航