數據結構之線性表(一)

線性表的順序存儲結構

1.頭文件SqList.h

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0

#define ElemType int
#define LIST_INIT_SIZE 10
#define LIST_INCREMENT 10

typedef int Status;

typedef struct
{
	ElemType *elem;
	int length;
	int listsize;
}SqList;

Status InitList(SqList &L);//初始化
Status DestoryList(SqList &L);//銷燬銷燬
Status ClearList(SqList &L);//清空線性表
Status GetElem(SqList L,int i,int &e);//獲取線性表中指定位置元素
Status ListInsert(SqList &L,int i,int e);//在指定位置插入元素
Status ListDelete(SqList &L,int i,int &e);//刪除指定位置元素,並用e返回值
Status LocateElem(SqList L,int e);//獲取元素子啊線性表中的位置
Status ListLength(SqList L);//獲取線性表的長度
Status ErgodicList(SqList L);//線性表的遍歷

2.函數實現SqList.cpp

#include <malloc.h>
#include <stdlib.h>  
#include <stdio.h>
#include "SqList.h"

Status InitList(SqList &L)
{
	L.elem=(ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
	if(!L.elem)
		exit(ERROR);
	L.length=0;
	L.listsize=LIST_INIT_SIZE;
	return OK;
}

Status DestoryList(SqList &L)
{
	free(L.elem);
	return OK;
}

Status ClearList(SqList &L)
{
	L.length=0;
	return OK;
}

Status GetElem(SqList L,int i,int &e)
{
	e=L.elem[i-1];
	return OK;
}

Status ListInsert(SqList &L,int i,int e)
{
	if(i>L.length+1 || i<1)
		return ERROR;
	if(L.length>=L.listsize)
	{
		ElemType *newbase=(ElemType *) realloc(L.elem,(L.listsize+LIST_INCREMENT)* sizeof(ElemType));
		if(!newbase)
			return ERROR;
		L.elem=newbase;
		L.listsize+=LIST_INCREMENT;
	}
	ElemType *q=&(L.elem[i-1]);//q爲插入位置
	ElemType *p;
	for(p=&(L.elem[L.length-1]);p>=q;p--)
		*(p+1)=*p;
	*q=e;
	L.length++;
	return OK;
}

Status ListDelete(SqList &L,int i,int &e)
{
	if(i<1 || i>L.length+1)
		return ERROR;
	e=L.elem[i-1];
	ElemType *p=&(L.elem[i-1]);//刪除的元素位置
	ElemType *q;
	for(q=p;q<=&(L.elem[L.length-1]);q++)
		*q=*(q+1);
	L.length-=1;
	return OK;
}

Status LocateElem(SqList L,int e)
{
	for(int i=0;i<L.length;i++)
	{
		if(L.elem[i]==e)
		{
			return OK;
			break;
		}
	}
	return ERROR;
}

Status ErgodicList(SqList L)
{
	for(int i=0;i<L.length;i++)
	{
		printf("第%d個:%d\n",i+1,L.elem[i]);
	}
	printf("線性表長度:%d\n",L.length);
	printf("線性表大小:%d\n",L.listsize);
	return OK;
}

3.主函數main.cpp

#include <stdio.h>
#include "SqList.h"

int main()
{
	SqList L;
	ElemType e;
	int flag;
	InitList(L);//初始化
	//賦值
	for(int i=1;i<12;i++)
	{
		ListInsert(L,i,i);//插入
	}

	GetElem(L,4,e);//獲取第四個元素
	ErgodicList(L);//遍歷
	printf("%d\n",e);//打印
	
	flag=LocateElem(L,e);//查找是否存在e
	printf("%d\n",flag);//查看返回結果

	ListDelete(L,6,e);//刪除
	ErgodicList(L);//遍歷
	printf("%d\n",e);//打印

	DestoryList(L);//銷燬
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章