题目:
解决方法:模拟、栈
1.模拟
[注]:
(1) 按顺序每k个进行分组
(2) 记录下一组的pre节点,方便组之间的连接
(3) 注意节点操作的内存变化和节点状态变化,比如pre、子函数的翻转之后!!!
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while(end.next!=null){
for(int i =0;i<k&&end!=null;i++)
end = end.next;
if(end==null)
break;
ListNode next = end.next;
end.next = null;
ListNode start = pre.next;
pre.next = reverse(start);
start.next = next;
pre = start;
end = start;
}
return dummy.next;
}
public static ListNode reverse(ListNode head){
ListNode pre = null;
ListNode curr = head;
while(curr!=null){
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
时间复杂度:O(n)
空间复杂度:O(1)
2.栈
注意其中pre和end的挪动,以及每次翻转与后面next的连接
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
Stack<ListNode> stack = new Stack<>();
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while(end.next!=null){
for(int i =0;i<k&&end!=null;i++){
end = end.next;
stack.push(end);
}
if(end==null)
break;
ListNode next = end.next;
while(!stack.isEmpty()){
pre.next = stack.pop();
pre = pre.next;
pre.next = null;
}
pre.next = next;
end = pre;
}
return dummy.next;
}