BM3 链表中的节点每k个一组翻转

发布时间 2023-05-06 20:29:41作者: two_q

描述

将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
 
数据范围:0n2000 ,1k2000 ,链表中每个元素都满足 0≤val1000
要求空间复杂度 O(1),时间复杂度 O(n)
 
例如:
给定的链表是 1→2→3→4→512345
对于k=2 , 你应该返回 2→1→4→3→5
对于k=3 , 你应该返回 3→2→1→4→5
 
 1 import java.util.*;
 2 
 3 /*
 4  * public class ListNode {
 5  *   int val;
 6  *   ListNode next = null;
 7  * }
 8  */
 9 
10 public class Solution {
11     /**
12      * 
13      * @param head ListNode类 
14      * @param k int整型 
15      * @return ListNode类
16      */
17     public ListNode reverseKGroup (ListNode head, int k) {
18         ListNode tail = head;
19 //        获得每个反转组的最后一个节点
20         for (int i = 0; i < k; i++) {
21             if (tail == null) {
22                 return head;
23             }
24             tail = tail.next;
25         }
26 
27 //        开始反转
28         // ListNode pre = null;
29         ListNode pre = new ListNode(-1);
30         ListNode cur = head;
31 
32         while (cur != tail) {
33             ListNode next = cur.next;
34             cur.next = pre;
35             pre = cur;
36             cur = next;
37         }
38         head.next = reverseKGroup(tail,k);
39 
40         return pre;
41     }
42 }