LeetCode Reorder List

本文介绍了一种链表重组算法,该算法将链表分为两部分并反转第二部分,然后交错合并两部分。文章提供了详细的实现步骤及源代码。
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	void reorderList(ListNode* head)
	{
		if(head == nullptr) return;
		int size = 0;
		ListNode *ptr = head;
		while(ptr != nullptr)
		{
			size++;
			ptr = ptr->next;
		}
		if(size <= 2) return;
		int breakpoint = (size + 1) / 2;
		int i = 0;
		ptr = head;
		while( i++ < breakpoint)
		{
			ptr = ptr->next;
		}
		ListNode *ptr2 = head;
		while(ptr2!= nullptr && ptr2->next != ptr)
			ptr2 = ptr2->next;
		if(ptr2 != nullptr)
			ptr2->next = nullptr;
		
		ListNode* newheadof2ndPart = reverseLinkedList(ptr);
		ptr = head;
		for(i = 0; i< breakpoint && ptr != nullptr && newheadof2ndPart != nullptr; i++)
		{
			ListNode*ptmp = ptr->next;
			ListNode*pnextnewhead = newheadof2ndPart->next;
			ptr -> next = newheadof2ndPart;
			newheadof2ndPart->next = ptmp;
			ptr = ptmp;
			newheadof2ndPart = pnextnewhead;
		}
	}
	
	ListNode* reverseLinkedList(ListNode* head)
	{
		if(head == nullptr) return nullptr;
		ListNode* newhead = reverseLinkedList(head->next);
		if(head-> next != nullptr)
		{
			head->next->next = head; //Error, 一定要搞清楚到底是哪个next哦
		}
		if(newhead == nullptr) newhead = head;
		head->next = nullptr;
		
		return newhead;
	}
	
};

 

转载于:https://www.cnblogs.com/whyandinside/p/5294258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值