25. k個一組翻轉鏈表node
仍然是鏈表處理問題,略微複雜一點,邊界條件得想清楚,畫畫圖就會比較明確了。函數
reverse函數表示從 front.next節點開始,一共k個節點作反轉。
即: 1>2>3>4>5 ,k = 2。當front爲1時,
執行reverse後:指針
1>3>2>4>5code
同上個題同樣,申請一個空的(無用的)頭指針指向第一個節點,會方便許多。ip
public ListNode reverseKGroup(ListNode head, int k) { ListNode ans = new ListNode(Integer.MAX_VALUE); ans.next = head; ListNode p = ans; while (ok(p.next, k)) { p = reverse(p, k); } return ans.next; } private boolean ok(ListNode p, int k) { while (k > 0 && p != null) { p = p.next; k--; } return k == 0; } private ListNode reverse(ListNode front, int k) { ListNode from = front.next; ListNode head = from; ListNode cur = from.next; ListNode tmp = null; while (k > 1 && cur != null) { tmp = cur.next; cur.next = from; from = cur; cur = tmp; k--; } head.next = cur; front.next = from; return head; }