[LeetCode] 025. Reverse Nodes in k-Group (Hard) (C++/Java)
來源:程序員人生 發布時間:2015-03-14 10:01:02 閱讀次數:3229次
索引:[LeetCode] Leetcode 題解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
025. Reverse Nodes in k-Group (Hard)
鏈接:
題目:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
代碼(github):https://github.com/illuz/leetcode
題意:
把1個鏈表每 k 個分為1組,每組內進行翻轉。
只能用常數級的空間。
分析:
這題比較考驗鏈表的操作,用遞歸做會比較方便,先找到下1組的節點,把本組反轉后再遞歸處理后面的節點。
代碼:
C++:
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (!head || !(head->next) || k < 2)
return head;
// count k nodes
ListNode *nextgp = head;
for (int i = 0; i < k; i++)
if (nextgp)
nextgp = nextgp->next;
else
return head;
// reverse
ListNode *prev = NULL, *cur = head, *next = NULL;
while (cur != nextgp) {
next = cur->next;
if (prev)
cur->next = prev;
else
cur->next = reverseKGroup(nextgp, k);
prev = cur;
cur = next;
}
return prev;
}
};
Java:
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
int cnt = 0;
// get next group
while (cur != null && cnt != k) {
cur = cur.next;
cnt++;
}
if (cnt == k) {
cur = reverseKGroup(cur, k);
// reverse
while (0 <= --cnt) {
ListNode tmp = head.next;
head.next = cur;
cur = head;
head = tmp;
}
head = cur;
}
return head;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈