LeetCode 25. K個一組翻轉鏈表

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; // 返回頭節點
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章