1. 程式人生 > >c語言:順序表的實現(二 ) 就地逆置,有序合併,大小調整。

c語言:順序表的實現(二 ) 就地逆置,有序合併,大小調整。

#include<iostream>  
#include<stdio.h>  
#define LIST_INIT_SIZE 100  
using namespace std;
struct Node
{
	int *elem;
	int Length;
	int Listsize;
};
//函式宣告部分
void Error(char *s);       //錯誤處理函式		
void printNode(Node &l);   //輸出函式
void InitNode(Node &L);    // 初始化函式
void CreatNode(Node &l);   //順序表建立函式
void InvertNode(Node &l);  //順序表就地逆置函式
void MeryNode(Node &L1, Node &L2,Node &L3);//順序表連線函式
void AdjustNode(Node &l);     //順序表調整函式

//函式定義部分

void Error(char *s)  //錯誤處理函式  
{
	cout << s << endl;
	exit(1);
}
void InitNode(Node &L) //初始化函式  
{
	L.elem = new int[LIST_INIT_SIZE];
	if (!L.elem)
		Error("Overflow!");
	L.Length = 0;
	L.Listsize = LIST_INIT_SIZE;
}
void CreatNode(Node &l) //建立順序表  
{
	int n;
	cout << "請輸入元素個數:";
	cin >> n;
	cout << "請輸入資料元素:" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> l.elem[i];
		l.Length++;
	}
	cout << "順序表建立成功!" << endl;
}

void InvertNode(Node &l)  //就地逆置函式  
{
	int     n = l.Length;
	for (int i = 0; i < n / 2; i++)
	{
		int  t = l.elem[n - i - 1];
		l.elem[n - i - 1] = l.elem[i];
		l.elem[i] = t;
	}
}
void MeryNode(Node &L1, Node &L2,Node &L3)//連線函式
{
	L3.Length = L1.Length + L2.Length;
	L3.elem = new int[L3.Length];
	if (!L3.elem)
		Error("Overflow!");
	int i = 0;
	int j = 0;
	int k = 0;
	while ((i < L1.Length) && (j < L2.Length)) //合併L1和L2
	{
		if (L1.elem[i] <= L2.elem[j])
		{
			L3.elem[k] = L1.elem[i];
			i++;
			k++;
		}
		else
		{
			L3.elem[k] = L2.elem[j];
			j++;
			k++;
		}
	}
	while (i < L1.Length)      //將L1的多餘部分鏈到L3上
	{
		L3.elem[k] = L1.elem[i];
		k++;
		i++;
	}
	while (j < L2.Length)       //將L2的多餘部分鏈到L3上
	{
		L3.elem[k] = L2.elem[j];
		k++;
		j++;
	}
}
void AdjustNode(Node &l)//調整函式
{
	int n = l.Length;
	int *temp = new int[n];
	int x = 0;
	int y = n - 1;
	for (int i = 0; i < n; i++)
	{
		if (l.elem[i] < 0)
		{
			temp[x] = l.elem[i];
			x++;
		}
		else
		{
			temp[y] = l.elem[i];
			y--;
		}
	}
	for (int j = 0; j < n; j++)
	{
		l.elem[j] = temp[j];
	}
	delete[] temp;
}

void printNode(Node &l) //輸出函式  
{
	for (int i = 0; i < l.Length; i++)
	{
		cout << l.elem[i] << " ";
	}
	cout << endl;
}
int main()             //主函式測試
{
	Node t1,t2,t3;
	//初始化三個結構體變數
	InitNode(t1);
	InitNode(t2);
	InitNode(t3);
	//對t1的操作實現
	CreatNode(t1);
	cout << "順序表t1逆置之前:" << endl;
	printNode(t1);
	cout << "順序表t1逆置之後:" << endl;
	InvertNode(t1);
	printNode(t1);
	cout << "順序表調整之後:" << endl;
	AdjustNode(t1);
	printNode(t1);
	//對t1的操作實現
	CreatNode(t2);
	cout << "順序表t2逆置之前:" << endl;
	printNode(t2);
	cout << "順序表t2逆置之後:" << endl;
	InvertNode(t2);
	printNode(t2);
	cout << "順序表調整之後:" << endl;
	AdjustNode(t2);
	printNode(t2);
	
	cout << "順序表合併之後:" << endl;
	MeryNode(t1, t2,t3);
	printNode(t3);
	return 0;
}