LeetCode 25. K個一組翻轉鏈表
/*
struct ListNode
{
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
*/
class Solution
{
public:
ListNode* reverseKGroup(ListNode* head, int K)
{
// 找到第K+1個節點,賦值給temp
ListNode* temp = head;
for (int i = 0; i < K; i++)
{
if (temp == nullptr) return head;
temp = temp->next;
}
// 翻轉head到temp之間的節點
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* next = head->next;
while(cur != temp)
{
cur->next = pre;
pre = cur;
cur = next;
if (cur != temp) next = cur->next;
}
// 此時,前K個節點的頭節點爲pre,尾節點爲head,下一個頭節點爲cur。
head->next = reverseKGroup(cur, K);
return pre; // 返回頭節點
}
}