数据结构中线性表的基本操作-合并两个线性表-依照元素升序排列

#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;
}

posted @ 2014-06-07 17:08  mfrbuaa  阅读(2214)  评论(0编辑  收藏  举报