25. 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 the list: 1-> 2-> 3-> 4-> 5

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

when k = 3, the return should be : 3-> 2-> 1-> 4-> 5

source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/reverse-nodes-in-k-group
the copyright collar button all network . Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

// c is written before the iterative method, for a long time before, and now they do this problem, to solve this problem with a recursive method to find out the core issues

// 1. What is the return value ------> is the head node is the first node of each child after flipping chain, identify the first node returns

// 2. Each sub-chain doing, that is, each layer of recursion doing, is to flip this sliver chain

// 3. Recursion in the end of the end of what conditions yes, yes count == 0,

/ **
 . * Definition List for Singly-linked
 * public class ListNode {
 * int Val;
 * ListNode Next;
 * ListNode (int X) {X = Val;}
 *}
 * /
class Solution {
    public ListNode reverseKGroup (ListNode head, k int) {
        IF (k == 1)
            return head;
        ListNode the p-= head;
        int SUM = 0;
        ! the while (the p-= null) // find out there are a number of nodes, we need to calculate the flip several sub chain, the chain is split to
        {
            SUM + =. 1;
            P = p.next;
        }
        int COUNT = SUM / K;
        return Reverse (head, COUNT, K);
        
    }
    public ListNode Reverse (ListNode head, COUNT int, int K )
    {
        IF (COUNT == 0)
            return head;
        ListNode pre = head;
        ListNode CUR = head.next;
        ListNode Next cur.next =;
        for (int I = 0; I <-K. 1; I ++)
        {
            cur.next = pre;
            pre = CUR;
            CUR = Next;
            IF (= null Next!)
                Next next.next =;
        }
        head.next = Reverse (CUR, - count, K); // here to note that, to reduce the count to 1, can not be used count--, this is the case, count is decremented by 1, but no recursion variable minus 1, or the original value of the
        return pre;
    }
}

Guess you like

Origin www.cnblogs.com/cold-windy/p/11366097.html