题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
if(head == null || k == 1) {
return head ;
}
ListNode PP = new ListNode(0) ;//返回参数的上一个结点
ListNode A = PP ;//已经处理好的链表的尾结点
ListNode D = null ;//还没处理的链表的头结点
ListNode B = null ;//正在处理的链表 在处理前的头结点
ListNode C = null ;//正在处理的链表 在处理前的尾结点
ListNode cur = head ;//当前结点
while(cur != null) {
//将待处理链表头部断开
A.next = null ;
B = cur ;
for(int i = 1 ; i < k ; i++) {
cur = cur.next ;
if(cur == null) {
break ;
}
}
if(cur == null) {
A.next = B ;
break ;
}
//此时K指向 待处理链表的尾结点
C = cur ;
D = cur.next ;
//将待处理链表 尾部断开
C.next = null ;
//处理待处理链表
C = fun(B) ;
//链接
A.next = C ;
B.next = D ;
//重新赋值
A = B ;
cur = D ;
}
return PP.next ;
}
/*
反转链表 返回反转后链表的头结点
*/
public ListNode fun(ListNode head) {
if(head == null || head.next == null) {
return head ;
}
ListNode pre = null ;
ListNode cur = head ;
while(cur != null) {
ListNode nxt = cur.next ;
cur.next = pre ;
pre = cur ;
cur = nxt ;
}
return pre ;
}
}
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录
查看13道真题和解析