题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
分段头插法:new一个辅助链表头出来---newhead
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) {
// write code here
int size = 0;
ListNode p = head;
while(p!=null){
size++;
p = p.next;
}
if(head == null || size < k) return head;
int n = size/k;//一共有多少组链表待翻转
ListNode newhead = new ListNode(-1);
newhead.next = head;
ListNode root = newhead;
for(int i = 0; i < n ;i++){
int j = 0;
while( j < k-1){
//一个子链表的翻转,头插法
p = head.next;
head.next = p.next;
p.next = newhead.next;
newhead.next = p;
j++;
}
//下一个子链表
newhead = head;
head = head.next;
}
return root.next;
}
}