1. 程式人生 > >面試題36:不使用額外空間將A、B兩連結串列元素交叉歸併

面試題36:不使用額外空間將A、B兩連結串列元素交叉歸併

#include "stdafx.h"
#include <iostream>
using namespace std;

//定義結點型別
struct Node 
{
	int m_value;//結點值
	Node* m_next;//指向下一個結點的指標
};

//建立一個長度為n的連結串列,返回頭結點的指標
Node* creat(int n)
{
	Node* head;
	Node* p1;
	Node* p2;
	for (int i=0; i<n; i++)
	{
		if (i == 0)
		{
			head = new Node();//建立頭結點
			cout << "請輸入第1個元素:";
			cin >> head->m_value;
			head->m_next = NULL;
			p1 = head;
		}
		else
		{
			p2 = new Node();
			cout << "請輸入第" <<i+1 << "個元素:";
			cin >> p2->m_value;
			p2->m_next = NULL;
			p1->m_next = p2;
			p1 = p2;
		}
	}
	return head;
}

//遞迴的實現A、B兩個連結串列的交叉歸併
void mergeRecursively(Node* headA, Node* headB) //注意:連結串列A的長度要大於等於連結串列B
{
	if (headA == NULL || headB == NULL)
	{
		return;
	} 
	
	mergeRecursively(headA->m_next, headB->m_next);
	headB->m_next = headA->m_next;
	headA->m_next = headB;
}

//非遞迴的實現A、B兩個連結串列的交叉歸併
void mergeNoRecursively(Node* headA, Node* headB)
{
	Node *pBCurrent = headB;
	Node *pBm_next = NULL;
	Node *pACurrent = headA;
    Node *pAm_next = NULL;

    while (pBCurrent != NULL)
    {
	   pBm_next = pBCurrent->m_next;//記錄下一個待插元素
	   pAm_next = pACurrent->m_next;//記錄插入位置

	   //插入元素
       pBCurrent->m_next = pACurrent->m_next;
	   pACurrent->m_next = pBCurrent;

	   pBCurrent = pBm_next; 
	   pACurrent = pAm_next;
    }
}

int main()
{
	Node* headA;
	Node* headB;
	Node* p;

	cout << "連結串列A: \n";
	headA = creat(4);
	cout << "連結串列B: \n";
	headB = creat(3);

	p = headA;
	//mergeRecursively(headA, headB);
	mergeNoRecursively(headA, headB);

	cout << "遞迴合併後的連結串列為:\n";	
	while (p != NULL)
	{
		cout << p->m_value << " ";
		p = p->m_next;
	} 
    cout << endl;
	return 0;
}


執行結果: