leetcode25. K flip list in groups

Give you a list, each k nodes to flip a group, you return to the list after the flip.

k is a positive integer that is less than or equal to the length of the list.

If the total number of nodes is not an integral multiple of k, then set the last remaining node original order.

Example:

Given this list: 1-> 2-> 3-> 4-> 5

When k = 2, it should be returned: 2-> 1-> 4-> 3-> 5

When k = 3, should be returned: 3-> 2-> 1-> 4-> 5

Description:

You can only use the extra space algorithm constants.
You can not just simply change the internal node values, but need to be the actual node exchange.

Ideas: Get list of two k, reversed intermediate, and operation of the various portions connected to the pointer. Code has detailed notes

 

/**
 * 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) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode end = dummy;
        while (end.next != null) {
            //1、找k个
            for (int i = 0; i < k && end != null; i++) end = end.next;
            //2、不足k个按原顺序,不用改变
            if (end == null) break;
            //3、记录反转链表的起点
            ListNode start = pre.next;
            //4、记录反转链表结尾的下一个节点
            ListNode next = end.next;
            //5、把反转链表的next赋值为null,方便调用reverse()
            end.next = null;
            //6、前节点的下一个节点是反转后的新头
            pre.next = reverse(start);
            //7、反转后的链表尾(之前的翻转起点)的next赋值为之前第4步记录的next
            start.next = next;
            //8、更新下一个要翻转k链表的前一个节点(也就是本次反转后的末尾)
            pre = start;
            //9、赋值end,为下一次循环的第一步做准备
            end = pre;
        }
        return dummy.next;
    }
    //翻转标准链表(最后节点的next是null),返回新链表的头
    private ListNode reverse(ListNode head) {
        ListNode pre = null;//前节点
        ListNode curr = head;//操作的节点
        while (curr != null) {
            //记录本次节点的下一个节点
            ListNode next = curr.next;
            //赋值本次节点的next为前节点
            curr.next = pre;
            //更新前节点和操作节点
            pre = curr;
            curr = next;
        }
        return pre;
    }
}

 

Published 554 original articles · won praise 10000 + · views 1.33 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104329354