マイクロソフト2014筆記試験問題21題解答(少し挫折)

1536 ワード

タイトルは上図の通りです.ここでは2つの解法を与える:1つ目は自分が考えている,時間複雑度O(n^2);第2の方法は実験室の大牛の考え,時間複雑度O(n)を実現した.
コードは次のとおりです.
void reorder1(NODE * root)
{
	int sum = -1, changeTimes, j;
	NODE * cur, *next, * stopNode;

	NODE * this1;
	static int insert_num = 0;

	assert(root != NULL);

	cur = root;
	while (cur)
	{
		sum++;
		cur = cur->next;
	}

	changeTimes = sum / 2;
	if (sum & 0x01)
	{
		changeTimes +=1;
	}
	insert_num = changeTimes;

	stopNode = root;
	while (changeTimes--)
	{
		stopNode = stopNode->next;
	}

	while (stopNode->next )
	{
		this1 = stopNode->next;
		stopNode->next = this1->next;
	
		insert_num++;
		cur = root;		
		j = sum - insert_num;
		while (j--)
		{
			cur = cur->next;
		}
		next = cur->next;

		cur->next = this1;
		this1->next = next;
	}
}

void reorder2(NODE * rootp)
{
	NODE * pHead1 = rootp, * pHead2 = rootp, *next1 , * next2, *pre2;
	int changeTiems, sum = -1;

	while (pHead1)
	{
		++sum;
		pHead1 = pHead1->next;
	}
	changeTiems = sum / 2;
	if (sum & 0x01)
	{
		changeTiems++;
	}
	while (changeTiems--)
	{
		pHead2 = pHead2->next;
	}
	
	next2 = pHead2->next;
	pHead2->next = NULL;

	for (pre2 = NULL; (pHead2 = next2) != NULL;)
	{
		next2 = pHead2->next;
		pHead2->next = pre2;
		pre2 = pHead2;
	}
	next2 = pre2;

	pHead1 = rootp;
	while ((pHead2 = next2) != NULL)
	{
		next2 = pHead2->next;

		next1 = pHead1->next;
		pHead1->next = pHead2;
		pHead2->next = next1;
		pHead1 = next1;
	}
}

テストを経て、运行は间违いありません!!!