1. Topic
Give you the head node head of the linked list, flip every k nodes, please return the modified linked list.
k is a positive integer whose value is less than or equal to the length of the linked list. If the total number of nodes is not an integer multiple of k, please keep the last remaining nodes in the original order.
You can't just change the value inside the node, but you need to actually swap the node.
Example 1:
Input : head = [1,2,3,4,5], k = 2
Output : [2,1,4,3,5]
Example 2:
Input : head = [1,2,3,4,5], k = 3
Output : [3,2,1,4,5]
Link to the topic: https://leetcode.cn/problems/reverse-nodes-in-k-group
2. Diagram
The title requires inverting in units of k linked list nodes in a linked list. What does it mean?
You can imagine dividing a very long linked list into many small linked lists, each of which has a length of k (if the length of the last one is less than k, there is no need to reverse), then reverse each small linked list, and finally splice all the reversed small linked lists together in the previous order.
In fact, the topic of the linked list does not require particularly strong logical reasoning. It mainly emphasizes the implementation of details, and the difficulty lies in the implementation of details. Although the general direction is known, it is likely to be messy when written .
So here are a few key points to keep in mind when doing this:
-
First, when reversing a sub-list, the end of the previous sub-list must be known
-
Second, the head of the next sublist must also know
-
Third, the head and tail of the currently reversed linked list must be known
3. Java sample code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null || k <= 1) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pointer = dummy;
while (pointer != null) {
// 记录上一个子链表的尾
ListNode lastGroup = pointer;
int i = 0;
for (; i < k; ++i) {
pointer = pointer.next;
if (pointer == null) {
break;
}
}
// 如果当前子链表的节点数满足 k, 就进行反转
// 反之,说明程序到尾了,节点数不够,不用反转
if (i == k) {
// 记录下一个子链表的头
ListNode nextGroup = pointer.next;
// 反转当前子链表,reverse 函数返回反转后子链表的头
ListNode reversedList = reverse(lastGroup.next, nextGroup);
// lastGroup 是上一个子链表的尾,其 next 指向当前反转子链表的头
// 但是因为当前链表已经被反转,所以它指向的是反转后的链表的尾
pointer = lastGroup.next;
// 将上一个链表的尾连向反转后链表的头
lastGroup.next = reversedList;
// 当前反转后的链表的尾连向下一个子链表的头
pointer.next = nextGroup;
}
}
return dummy.next;
}
private ListNode reverse(ListNode head, ListNode tail) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null, temp = null;
while ((head != null) && (head != tail)) {
temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
}
Results of the: