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}.
解析:(1)把链表分割成A,B两部分。
(2)对链表第二部分进行反转。
(3)合并链表A和反转后的B链表。
//对单向链表进行重排序
#include<iostream>
#include<random>
using namespace std;

//链表数据结构
struct ListNode
{
	int val;
	ListNode *next;
};

//在链表末尾追加元素
void appendTail(ListNode **pHead, int val)
{
	ListNode *pNew = new ListNode;
	pNew->next = NULL;
	pNew->val = val;

	if (*pHead == NULL)
	{
		*pHead = pNew;
	}
	else
	{
		ListNode *tmp = *pHead;
		while (tmp->next)
		{
			tmp = tmp->next;
		}
		tmp->next = pNew;
	}
}

//正序输出链表
void show(ListNode *pHead)
{
	while (pHead)
	{
		cout << pHead->val << " ";
		pHead = pHead->next;
	}
	cout << endl;
}

//反转链表
void reverseList(ListNode *&head)
{
	if (head == NULL || head->next == NULL)
		return;
	ListNode *p = head->next;
	head->next = NULL;
	while (p)
	{
		ListNode *tmp = p;
		p = p->next;
		tmp->next = head;
		head = tmp;
	}
}

//合并两个链表
void union_list(ListNode *pHead1, ListNode *pHead2)
{
	ListNode *p = pHead1;
	ListNode *q = pHead2;
	while (q)
	{
		ListNode *tmp = q;
		q = q->next;
		tmp->next = p->next;
		p->next = tmp;
		p = tmp->next;
	}
}

//重排序链表
void reorderList(ListNode *head)
{
	int num = 0;
	ListNode *p = head;
	while (p != NULL)
	{
		num++;
		p = p->next;
	}
	ListNode *q = head;
	for (int i = 0; i < (num + 1) / 2; ++i)
	{
		if (i == ((num+1)/2 - 1))
		{
			ListNode *tmp = q;
			q = q->next;
			tmp->next = NULL;
		}
		else
		{
			q = q->next;
		}	
	}
	reverseList(q);
	union_list(head, q);
}

int main()
{
	ListNode *pHead = NULL;
	for (int i = 1; i < 1; ++i)
	{
		appendTail(&pHead, i);
	}
	
	reorderList(pHead);
	show(pHead);
	system("pause");
	return 0;
}

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