No matter what everyone in the world says, I think my feelings are right. No matter what other people think, I never break my rhythm. Like things naturally can insist, do not like how also can not long.

LeetCode: the original address

Topic request

You are given a linked list, each k nodes in a group of flipped, please return to the flipped list.

K is a positive integer whose value is less than or equal to the length of the list.

If the total number of nodes is not an integer multiple of k, keep the last remaining nodes in the same order.

Advanced:

Can you design an algorithm that only uses constant extra space to solve this problem? You can’t just change the values inside the nodes, you need to actually swap nodes.

Example 1:

Enter: head = [1.2.3.4.5], k = 2Output:2.1.4.3.5]
Copy the code

Example 2:

Enter: head = [1.2.3.4.5], k = 3Output:3.2.1.4.5]
Copy the code

Example 3:

Enter: head = [1.2.3.4.5], k = 1Output:1.2.3.4.5]
Copy the code

Example 4:

Enter: head = [1], k = 1Output:1]
Copy the code

Tip:

  • The number of nodes in the list is in range SZ
  • 1 <= sz <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= sz

Train of thought

  • Divide into k groups and reverse them
  • Chain the reversed list recursively

code

Const reverse = (a, b) => {let pre, cur, NXT; cur = a; while (cur! Next = pre; pre = cur; cur = NXT;}  /** * @param {ListNode} head * @param {number} k * @return {ListNode} */ var reverseKGroup = function (head, k) { if (head == null) { return head; } let a = head, b = head; for (let i = 0; i < k; I++) {base case if (b == null) {return head;} else {b = b.ext; } // reverseKGroup(a, b) = reverseKGroup(b, k);Copy the code