題目:
這道題如果沒有空間的限制的話,我們可以将前k個數按順序存入棧中,再依次取出,根據棧的特性,他們是倒序的排列,可惜空間負責度是O(K)
是以我們隻能選用其他的方法
最終,我選擇了尾插法
代碼如下:
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode tail = dummy;
ListNode cur=null;
ListNode head1=null;
while (true) {
int count = 0;
while (tail != null && count != k) {
count++;
tail = tail.next;
}
if (tail == null) break;
head1 = pre.next;
while (pre.next != tail) {
cur = pre.next;
pre.next = cur.next;
cur.next = tail.next;
tail.next = cur;
}
pre = head1;
tail = head1;
}
return dummy.next;
}
}
運作結果如下: