给定一个单链表的头节点head,和一个正数k
实现k个节点的小组内部逆序,如果最后一组不够k个就不调整例子:
调整前∶1 ->2-> 3-> 4 ->5-> 6->7 ->8, k = 3
调整后∶3-> 2 ->1-> 6->5-> 4 ->7 -> 8
先准备两个子方法;
子方法1:获取从当前节点开始的第K个节点; 若不足K个,返回null。
public static Node getKGroupEnd (Node start, int k) {
while (--k != 0 ) {
if (start == null) {
return start;
}
start = start.next;
}
return start;
}
子方法2:给定一个头结点和尾节点,对二者及其中间节点反转;
例: 1 ->2-> 3-> 4
若传入(1,3),则返回 3->2->1->4
public static void reverse (Node start, Node end) {
end = end.next;
Node pre = end;
Node next = null;
while (start != end) {
next = start.next;
start.next = pre;
pre = start;
start = next;
}
}
主方法:
获取头结点;
满足K个时,每K个一组逆序;
若不满足K个,直接返回头结点;
public static Node reverseKGroupList (Node head, int K) {
Node start = head;
Node end = getKGroupEnd(start,K);
if (end == null) {
return head;
}
//获取头节点
head = end;
reverse(start,end);
Node lastEnd = start;
while (lastEnd.next != null) {
start = lastEnd.next;
end = getKGroupEnd(start,K);
//若不满足K个,返回头结点
if (end == null) {
return head;
}
//K个一组逆序
reverse(start,end);
lastEnd.next = end;
lastEnd = start;
}
return head;
}
测试:1 ->2-> 3-> 4 ->5-> 6 , K=2
调整前:
1 2 3 4 5 6
调整后:
2 1 4 3 6 5