LeetCode.25 Reverse Nodes in k-Group

本文详细解析了链表中每K个一组进行翻转的复杂算法实现,通过递进的方式逐步阐述如何处理链表节点的翻转操作,确保算法的正确性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写得不简洁,1h。总结一个清晰简洁的版本。

class Solution
{
public:
	void reversList(ListNode* head, ListNode* tail, ListNode* prev_sec_tail, ListNode* next_sec_head)
	{
		if (!head)
		{
			return;
		}

		ListNode* head_origin = head;
		ListNode* tail_origin = tail;

		ListNode* curr = head;
		ListNode* next = head->next;
		ListNode* next_next = nullptr;

		if (next)
		{
			next_next = next->next;
		}

		while (next)
		{
			next->next = curr;

			if (next == tail)
			{
				break;
			}

			curr = next;
			next = next_next;

			if (next)
			{
				next_next = next->next;
			}
		}

		head_origin->next = next_sec_head;

		if (!prev_sec_tail)
		{
			prev_sec_tail = tail_origin;
		}
		else
		{
			prev_sec_tail->next = tail_origin;
		}

		prev_sec_tail = head_origin;
	}

	ListNode* reverseKGroup(ListNode* head, int k) 
	{
		if (k < 2)
		{
			return head;
		}

		ListNode* curr_sec_head = head;
		ListNode* curr_sec_tail = head;
		
		ListNode* prev_sec_tail = nullptr;
		ListNode* next_sec_head = nullptr;

		bool is_get_final_head = false;
		ListNode* final_head = head;

		while (true)
		{
			int idx = 0;

			while (idx < k - 1 && curr_sec_tail)
			{
				++idx;

				curr_sec_tail = curr_sec_tail->next;
			}

			if (idx != k - 1 || !curr_sec_tail)
			{
				break;
			}
			else
			{
				next_sec_head = curr_sec_tail->next;

				reversList(curr_sec_head, curr_sec_tail,prev_sec_tail,next_sec_head);

				if (!is_get_final_head && curr_sec_tail)
				{
					final_head = curr_sec_tail;
					is_get_final_head = true;
				}

				prev_sec_tail = curr_sec_head;
				curr_sec_tail = next_sec_head;
				curr_sec_head = next_sec_head;
			}
		}

		return final_head;
	}
};

2018-08-16 16:57:11 L.137'25369 T2925587773.K.F3783850860


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值