题解 | #链表中的节点每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
//递归
//有k个节点,就翻转,没有就返回头节点
//得到翻转的头和尾,下一个节点是下一组结点(翻转/ 不翻转)的头
ListNode pre = null, cur = head, tail = head;
int count = 0;
while( count < k){
if( tail == null ){return head;}
tail = tail.next;
count++;
}
while(cur!=tail ){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}//pre头节点,head:尾结点, cur:下一组
head.next = reverseKGroup( cur, k);
return pre;
}
}
/*
* 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
//递归
//有k个节点,就翻转,没有就返回头节点
//得到翻转的头和尾,下一个节点是下一组结点(翻转/ 不翻转)的头
ListNode pre = null, cur = head, tail = head;
int count = 0;
while( count < k){
if( tail == null ){return head;}
tail = tail.next;
count++;
}
while(cur!=tail ){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}//pre头节点,head:尾结点, cur:下一组
head.next = reverseKGroup( cur, k);
return pre;
}
}