抱歉,我就是交换了值,用数组保存的,没想到过了 -3-……
1 public ListNode reverseKGroup(ListNode head, int k) {
2 ListNode p = head, p2 = p;
3 int[]a=new int[k];
4
5 if (p == null) return head;
6 while (true) {
7 p2=p;
8 for (int i = 0; i < k ; i++) {
9 if (p2 != null) {
10 a[i]=p2.val;
11 p2 = p2.next;
12 } else return head;
13 }
14 p2=p;
15 for (int i = 0; i < k ; i++) {
16 p2.val=a[k-1-i];
17 p2=p2.next;
18 }
19 if (p2==null)return head;
20 else p=p2;
21 }
22 }
本文介绍了一种链表操作算法,实现链表节点值的K组翻转。通过使用数组临时保存每组K个节点的值,再将这些值按相反顺序赋回节点,达到链表局部反转的效果。此方法在链表处理中具有实用价值。

被折叠的 条评论
为什么被折叠?



