题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/*
* 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
ListNode l = head;
int length = 0;
while(l != null){
l = l.next;
length++;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode cur = head;
ListNode pre = newHead;
int c = length/k;
while(c != 0){
for(int i = 1;i < k;i ++){
ListNode node = cur.next;
cur.next = node.next;
node.next = pre.next;
pre.next = node;
}
pre = cur;
cur = cur.next;
c--;
}
return newHead.next;
}
}

美团成长空间 2667人发布