Reorder List

Given a singly linked list L : L0 → L1 → ··· → Ln−1 → Ln, reorder it to: L0 → Ln → L1 →
Ln−1 → L2 → Ln−2 → ···
You must do this in-place without altering the nodes’ values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

思路:

找到中间节点,断开

后半截链表reverse

合并两个链表


#include <iostream>
using namespace std;

struct LinkNode{
	int data;
	LinkNode *next;
	LinkNode(int x):data(x),next(NULL){}
};

class Solution
{
	void reorderList(LinkNode *head)
	{
		if(head == NULL || head->next == NULL) return;
		LinkNode *pre = NULL;
		LinkNode *fast=head,*slow=head;
		while(fast && fast->next)
		{
			pre=slow;
			slow=slow->next;
			fast=fast->next->next;
		}
		pre->next = NULL;//从中间cut

		slow = reverse(slow);//对第二部分链表逆序

		//merge 两个链表
		LinkNode *cur = head;
		while(cur->next)
		{
			LinkNode *tmp = cur->next;
			cur->next = slow;
			slow = slow->next;
			cur->next->next = tmp;
			cur=tmp;
		}
		cur->next=slow;//在偶数个时,两部分相等。但是在奇数个时,slow会更长。如果slow还存在,那么接上slow后面的。如果不存在,就接null。
	}

	LinkNode *reverse(LinkNode *head)
	{
		LinkNode *pre = NULL;
		while(head)
		{
			LinkNode *tmp = head->next;
			head->next = pre;
			pre=head;
			head=tmp;
		}
		return pre;
	}
}




你可能感兴趣的:(Reorder List)