Niuke.com High Frequency Algorithm Question Series - BM3 - Nodes in the linked list are flipped every k
Topic description
Flip the nodes in the given linked list every k groups, and return the flipped linked list. If the number of nodes in the linked list is not a multiple of k, keep the last remaining nodes as they are. You cannot change the value in the node, you can only change it the node itself.
See the original title: Nodes in the BM3 linked list are flipped in groups of k
Solution 1: Recursion
Use recursive method to process each k group of nodes, the specific processing method is as follows:
- First, use tail to record the tail of each flip, which is the k+1th node, start from the head node, traverse the linked list, and find the k+1th node. If the current number of nodes is not enough, return directly without reversing ;
- Then start traversing from the head of the linked list, flip the node and record the reversed head pre and tail node head;
- Then recursively process the following linked list nodes starting from tail, and point head to the recursively processed linked list;
- The returned new header is the header node of the reversed new linked list.
code
public class Bm003 {
/**
* 递归
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public static ListNode reverseKGroup(ListNode head, int k) {
// 找到每次翻转的尾部
ListNode tail = head;
// 遍历k次到尾部
for (int i = 0; i < k; i++) {
// 如果不足k到了链表尾部,直接返回,不翻转
if (tail == null) {
return head;
}
tail = tail.next;
}
// 翻转时需要的前序和当前节点
ListNode pre = null, cur = head;
// 在到达当前段尾部节点前
while (cur != tail) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
// 当前尾部指向下一段要翻转的链表
head.next = reverseKGroup(tail, k);
return pre;
}
public static void main(String[] args) {
ListNode head = ListNode.testCase2();
System.out.println("翻转之前");
ListNode.print(head);
// 当k=2时
ListNode newHead = reverseKGroup(head, 2);
System.out.println("当k=2时,翻转之后");
ListNode.print(newHead);
ListNode head1 = ListNode.testCase2();
// 当k=3时
ListNode newHead2 = reverseKGroup(head1, 3);
System.out.println("当k=3时,翻转之后");
ListNode.print(newHead2);
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。