题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
对于最后一个K的长度我们不需要进行翻转,故而每次可以判断一下当前的是否满足长度为K。
满足,就使用头插法来进行链表翻转。对于最后一个如果不满足长度为K,我们直接链接到最后即可。
代码如下:
public ListNode reverseKGroup (ListNode head, int k) {
ListNode dummyNode = new ListNode(0);
ListNode ptr = head, qtr = dummyNode, temp;
while(ptr != null){
int count = k;
temp = ptr;
while(count > 0 && temp != null){
temp = temp.next;
count--;
}
temp = ptr;
if(count > 0) { // 判断最后一轮情况如何
qtr.next = ptr;
break;
}else{
// 链表翻转
count = k;
while(count > 0 && temp != null){
ptr = ptr.next;
temp.next = qtr.next;
qtr.next = temp;
temp = ptr;
count--;
}
count = k;
// 移动指针到下一个位置
while(count > 0 && qtr.next != null){
qtr = qtr.next;
}
}
}
return dummyNode.next;
}