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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容