25. Reverse Nodes in k-Group

题目25. 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
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || k == 1){
            return head;
        }
        ListNode tempHead = new ListNode(1);
        
        int count = 1;
        ListNode node = head;
        ListNode reverseStartNode = head;
        ListNode reverseHead = tempHead;
        while(node != null){
            if(count % k == 0){
                ListNode tempNode = node.next;
                int num = 1;
                ListNode reverseNode = reverseStartNode;
                ListNode temp = null;
                while(num <= k){
                    temp = reverseNode.next;
                    reverseNode.next = reverseHead.next;
                    reverseHead.next = reverseNode;
                    reverseNode = temp;
                    num++;
                }
                reverseHead = reverseStartNode;
                reverseStartNode = tempNode;
                node = tempNode;
            }else{
                node = node.next;
            }
            count ++;
        }
        count--;
        System.out.println(count);
        if(k > count) {
            return head;
        }
        
        if(count % k != 0){
           reverseHead.next = reverseStartNode;
        }
        return tempHead.next;
    }
}

你可能感兴趣的:(25. Reverse Nodes in k-Group)