首页 > 代码库 > 【LeetCode】Reverse Nodes in k-Group 解题报告

【LeetCode】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

【解析】

题意:把原始链表k个k个的反转,如果最后剩余的不到k个结点,那么保持不变。

没什么特殊算法,我觉得重点在于怎么不用额外的空间反转k个结点,用三个指针 curtail, curhead, posthead,curtail 指向反转后的尾结点,curhead 指向反转后的头结点,posthead 是反转过程中 curhead 的后一个结点,用于辅助反转。这个方法可以对照题目 【LeetCode】Reverse Linked List II 解题报告 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k < 2) return head;
        
        ListNode prehead = new ListNode(0);
        prehead.next = head;
        int cnt = 0;
        ListNode node = head;       //迭代结点
        ListNode lasttail = prehead;//上次k个结点反转后的尾结点
        ListNode curtail = head;    //这次要反转的k个结点的尾结点
        ListNode curhead = head;    //这次要反转的k个结点的头结点
        ListNode posthead = null;   //这次要反转的k个结点的头结点后面的一个结点
        while (node != null) {
            cnt++;
            node = node.next;
            
            //反转这k个结点
            if (cnt == k) {
                ListNode tmp = curtail.next;
                while (tmp != node) {
                    posthead = curhead;
                    curhead = tmp;
                    tmp = tmp.next;
                    curhead.next = posthead;
                }
                lasttail.next = curhead;//把这次反转的k个结点接到上次的k个结点后
                lasttail = curtail;
                curtail = node;
                curhead = node;
                cnt = 0;
            }
            
        }
        
        //如果后面还有少于k个的结点,直接把其接到之前的链表上
        lasttail.next = curhead;
        
        return prehead.next;
    }
}


相关题目: 【LeetCode】Reverse Linked List II 解题报告 

【LeetCode】Reverse Nodes in k-Group 解题报告