資料結構中線性表的基本操作-合併兩個線性表-按照元素升序排列

期待一片自己的藍天發表於2014-05-07
#include<iostream>
#include<stdlib.h>

#define	LIST_INIT_SIZE 10/*線性表初始長度*/
#define LIST_CREATENT 2/*每次的增量*/

typedef int ElemType;

using namespace std;

typedef struct SqList/*線性表的資料結構定義*/
{
	ElemType *elem;/*線性表基址*/
	int length;/*當前線性表所含的元素個數*/
	int listSize;/*已經分配的長度*/
}SqList;

void InitList(SqList &L)/*線性表初始化*/
{
	L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
	L.length = 0;
	L.listSize = LIST_INIT_SIZE;
}

void DestoryList(SqList &L)/*銷燬一個線性表*/
{
	free(L.elem);
	L.length = 0;
	L.listSize = 0;
}

void ClearList(SqList &L)/*清空一個線性表*/
{
	L.length = 0;
}

void listInsert(SqList &L, int k)/*往線性表中新增一個元素,按照元素從小到大的順序*/
{
	ElemType *p, *q;
	if (L.length == L.listSize)/*線性表已經沒有空間了,需要分配新空間*/
	{
		ElemType *newBase;
		newBase = (ElemType*)realloc(L.elem,(L.listSize+LIST_CREATENT)*sizeof(ElemType));
		if (!newBase)
			exit(1);
		L.elem = newBase;
		L.listSize += LIST_CREATENT;
	}
	p = q = L.elem;/*記錄元素線性表開始的位置*/
	if (L.length == 0)/*如果表中沒有元素,則直接插入元素即可*/
	{
		*p = k;
	}
	else/*線性表中有元素,則需要進行比較,找到合適的插入位置*/
	{
		int i = 0;
		for (i = 0; i != L.length - 1; ++i, ++q);/*將指標指向線性表的最後一個元素*/
		for (i = 0; i != L.length&&k > *p; ++i, ++p);/*找到要插入的位置*/
		for (--p; q != p; *(q + 1) = *q, --q);/*從後往前依次移動元素*/
		*(q + 1) = k;/*找到插入位置*/
	}
	++L.length;/*線性表長度增加1*/
}

void createList(SqList &L, int *k, int n)/*建立一個線性表*/
{
	int i;
	for (i = 0; i < n; ++i)
		listInsert(L,k[i]);
}

void ListDelete(SqList &L, int k)/*刪除線性表中的一個元素*/
{
	ElemType *p, *q;
	p = q = L.elem;
	int i,flag=1;	
	for (i=0; i != L.length; ++p, ++q, ++i)
	{
		if (*p == k)
		{
			for (; i != L.length; ++p, ++i)
				*p = *(p + 1);
			--L.length;
			cout << "Delete :" << k << endl;
			flag = 0;
			i = L.length;
		}
	}
	if (flag)
		cout << "Have not been found " << k << endl;
}

void ListTraveller(SqList L)/*遍歷線性表*/
{
	int i;
	ElemType *p;
	for (i = 0,p=L.elem; i != L.length; ++i)
		cout << *p++ << " ";
	cout << "\n";
}

bool LocateElem(SqList L,int k)
{
	ElemType *p;
	int i;
	for (i = 0,p=L.elem; i != L.length; ++i,++p)
		if (*p == k)
			return true;
	return false;
}

void unionSq(SqList &aL, SqList b)/*合併兩個線性表*/
{
	int i, bl;
	ElemType *bp;
	for (i = 0,bl=b.length,bp=b.elem; i != bl;++i,++bp)
		if (!LocateElem(aL, *bp))
			listInsert(aL,*bp);
}

int main()
{
	ElemType a[] = { 1, 3,5,7,9,11,12,13}, b[] = { 2,6,8,25,32,1};
	int a_len = sizeof(a) / sizeof(ElemType);
	int b_len = sizeof(b) / sizeof(ElemType);
	SqList sa, sb;
	InitList(sa);
	InitList(sb);
	createList(sa, a, a_len);
	createList(sb, b, b_len);
	ListTraveller(sa);
	ListTraveller(sb);
	unionSq(sa,sb);
	cout << "合併後的線性表:" << endl;
	ListTraveller(sa);
	return 0;
}

相關文章