题解 | #链表中的节点每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) {
// write code here
if(head ==null || head.next==null) return head;
ListNode tail = head;
ListNode begin = tail;
for(int i=0;i<k;i++){
if(tail==null) return head;
tail = tail.next;
}
for(int i=0;i<k;i++){
if(i==k-1){
begin.next = null;
}else{
begin = begin.next;
}
}
ListNode newHead = reverse(head);
head.next = reverseKGroup(tail,k);
return newHead;
}
public ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur!=null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}