1. 程式人生 > >實現順序表各種基本運算的演算法

實現順序表各種基本運算的演算法

 sqlist.cpp

#include "stdio.h"
#include "malloc.h"
#define MaxSize 50
typedef char ElemType;
typedef struct{
	ElemType data[MaxSize];                //存放順序表元素
	int length;                            //存放順序表的長度
} SqList;                                      //宣告順序表的型別

void CreateList(SqList *&L,ElemType a[],int n){    //整體建立順序表
	L = (SqList *)malloc(sizeof(SqList));
	for(int i=0;i<n;i++)
		L -> data[i] = a[i];
	L -> length = n;
}

void InitList(SqList *&L){                        //初始化線性表
	L = (SqList *)malloc(sizeof(SqList));     //分配存放線性表的空間
	L -> length = 0;
}

void DestroyList(SqList *&L){                     //銷燬線性表
	free(L);
}

bool ListEmpty(SqList *L){                        //判斷線性表是否為空表
	return(L -> length == 0);
}

int ListLength(SqList *L){                        //求線性表的長度
	return(L -> length);
}

void DispList(SqList *L){                         //輸出線性表
	for(int i=0;i<L -> length;i++)
		printf("%c",L -> length);
	printf("\n");
}

bool GetElem(SqList *L,int i,ElemType e){         //求線性表中第i個元素的值
	if(i < 1 || i > L -> length)
		return false;
	e = L -> length;
	return true;
}

int LocateElem(SqList *L,ElemType e){            //查詢第一個值域為e的元素的序號
	int i=0;
	while(i<L -> length && L -> data[i] != e)
		i++;
	if(i>L -> length)
		return 0;
	else
		return i+1;
}

bool ListInsert(SqList *&L,int i,ElemType e){    //插入第i個元素
	int j;
	if(i < 1 || i > L -> length + 1)
		return false;
	i--;                                     //將順序表位序轉化為data下標
	for(j=L -> length;j>i;j--)               //將data[i]及後面的元素後移一個位置
		L -> data[j] = L -> data[j-1];
	L -> data[i] = e;                        //順序表長度+1
	L -> length++;
	return true;
}

bool ListDelete(SqList *&L,int i,ElemType &e){   //刪除第i個元素
	int j;
	if(i < 1 || i > L -> length)
		return false;
	i--;                                     //將順序表位序轉化為data下標
	e = L ->data[i];
	for(j = i; j < L -> length - 1; j++)     //將data[i]及後面的元素前移一個位置
		L -> data[j] = L -> data[j+1];
	L -> length--;                           //順序表長度-1
	return true;
}

main.cpp

#include "sqlist.cpp"
int main(){
	SqList *L;
	ElemType e;
	printf("順序表的基本運算如下:\n");
	printf("  (1)初始化順序表L\n");
	InitList(L);
	printf("  (2)依次插入 a,b,c,d,e 元素\n");
	ListInsert(L, 1, 'a');
	ListInsert(L, 2, 'b');
	ListInsert(L, 3, 'c');
	ListInsert(L, 4, 'd');
	ListInsert(L, 5, 'e');
	printf("  (3)輸出順序表L:");
	DispList(L);
	printf("  (4)順序表L長度:%d\n",ListLength(L));
	printf("  (5)順序表L為%s\n",(ListEmpty(L)?"空":"非空"));
	GetElem(L, 3, e);
	printf("  (6)順序表L的第3個元素:%c\n",e);
	printf("  (7)元素a的位置:%d\n",LocateElem(L, 'a'));
	printf("  (8)在第4個元素的位置上插入f元素\n");
	ListInsert(L, 4, 'f');
	printf("  (9)輸出順序表L:");
	DispList(L);
	printf("  (10)刪除L的第3個元素\n");
	ListDelete(L, 3, e);
	printf("  (11)輸出順序表L:");
	DispList(L);
	printf("  (12)釋放順序表L\n");
	DestroyList(L);
	return 1;
}