publicListNodereverseKGroup(ListNode head,int k){//简化计算,先遍历获取链表长度int len =getLength(head);//计算需要反转的次数int n = len/k;//简历虚拟头节点ListNode vhead =newListNode(-1);//current指向每次头插法插入的头节点ListNode current = vhead;//iter用于遍历给定链表ListNode iter = head;//n次反转for(int i=0;i<n;i++){//k个一组反转for(int j=0;j<k;j++){//记录需要遍历的下一个节点ListNode next = iter.next;//头插法进行节点插入
iter.next = current.next;
current.next = iter;//继续遍历
iter = next;}//将current指向当前的最后一个节点,也是下次头插法的头节点for(int l=0;l<k;l++){
current = current.next;}}//不足k个,直接拼接if(iter!=null){
current.next = iter;}//返回k个一组反转后的链表return vhead.next;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
publicintgetLength(ListNode head){ListNode current = head;int count =0;while(current!=null){
count++;
current = current.next;}return count;}
1
2
3
4
5
6
7
8
9
穿针引线法实现
publicListNodereverseKGroup(ListNode head,int k){//为了方便插入,简历虚拟头节点ListNode vhead =newListNode(-1);//pre指向拼接时的前一个节点ListNode pre = vhead;//计算反转次数int n =getLength(head)/k;//current用于遍历给定链表ListNode current = head;//n次反转for(int i=0;i<n;i++){//left指向反转前的第一个元素ListNode left = current;//找到当前的第K个元素for(int j=0;j<k-1;j++){
current = current.next;}//right指向反转前的最后一个元素ListNode right = current;//post指向拼接时的后一个节点ListNode post = current.next;//right必须置空,否则后面的元素会一起反转
right.next =null;//反转
right =reverse(left);//拼接
pre.next = right;
left.next = post;//下次拼接时的前一个节点变成left
pre = left;//下一次反转从post开始计数
current = post;}//最后不足K个,直接拼接if(current!=null){
pre.next = current;}//返回反转结果return vhead.next;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
publicListNodereverse(ListNode head){ListNode pre =null;ListNode current = head;while(current!=null){ListNode next = current.next;
current.next = pre;
pre = current;
current = next;}return pre;}
1
2
3
4
5
6
7
8
9
10
11
publicintgetLength(ListNode head){ListNode current = head;int count =0;while(current!=null){
count++;
current = current.next;}return count;}