第二章、線性表

線性表

2.1、定義

線性表:是最常用的一種數據結構,一個線性表是n個數據元素的有限序列。
數據項:一個數據元素可以由若干個數據項組成。例如用戶表中的 用戶名
記錄:數據元素稱爲記錄
文件:含有大量記錄的線性表又稱爲文件。
抽象數據類型線性表的定義如下:
在這裏插入圖片描述

2.2 線性表的順序表示和實現

順序表示:是指用一組地址連續的存儲單元依次存儲線性表的數據元素。
假定線性表的每個元素需要佔用l個存儲單元,並以所佔的第一個單元的存儲地址作爲數據元素的存儲位置。則線性表中第i+1個數據元素的位置爲
LOC(ai+1) = LOC(ai)+l
線性表的第i個元素ai的存儲位置爲:
LOC(ai) = LOC(ai) + (i-1)*l
在這裏插入圖片描述

2.2.1、公共常量和類型定義

通用常量定義

//函數結果狀態代碼
constexpr auto TRUE = 1;
constexpr auto FALSE = 0;
constexpr auto OK = 1;
constexpr auto ERROR = 0;
constexpr auto INFEASIBLE = -1;
//Status是函數的類型,其值是函數結果狀態碼
typedef int			Status;

c結構圖定義

#define LIST_INIT_SIZE	100	//線性表存儲空間的初始化配量
#define LISTINCREMENT	10	//線性表存儲空間的分配增量

typedef int	 ElemType;		//當前方法中使用的元素

typedef struct{
ElemType *elem;		//存儲空間地址
int	length;			//當前長度
int listsize;		//當前分配的存儲容量
}SqList;

elem:指示線性表的基地址
length:指示線性表的當前長度

  • 初始化方法
Status InitList(SqList &sqList)
{
	sqList.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
	if (!sqList.elem) {					//存儲分配失敗
		exit(OVERFLOW);	
	}
	sqList.length = 0;					//空表長度爲0
	sqList.listsize = LIST_INIT_SIZE;	//初始存儲容量
	return OK;
} //InitList
  • 插入元素
Status ListInsert(SqList &sqList,int i, ElemType e)
{
	//在順序線性表sqList中第i個位置之前插入新的元素e,
	if (i<1 || i>sqList.length + 1) 
	{
		return ERROR;
	}
	//當前存儲空間已滿,增加分配
	if (sqList.length >= sqList.listsize)
	{
		ElemType* newbase = (ElemType*)realloc(sqList.elem, (sqList.listsize + LISTINCREMENT) * sizeof(ElemType));
		if (!newbase)
		{
			exit(OVERFLOW);					//分配空間失敗
		}	
		sqList.elem = newbase;				//新基址
		sqList.listsize += LISTINCREMENT;	//增加存儲容量
	}
	ElemType* elem = &(sqList.elem[i - 1]);
 	for (ElemType* p = &(sqList.elem[sqList.length - 1]); p >= elem; --p)
	{
		*(p + 1) = *p;
	}
	*elem = e;
	++sqList.length;
	return OK;
}
  • 刪除元素
//在順序線性表sqList中刪除第i個元素,並用e返回其值
Status ListDelete(SqList &sqList, int i, ElemType &e)
{
	if (i < 1 || (i > sqList.length))
	{
		return ERROR;							//i值不合法
	}
	ElemType *elem = &(sqList.elem[i - 1]);		//elem爲被刪除的元素位置
	e = *elem;
	ElemType *tail = sqList.elem + sqList.length - 1; //被刪除元素的值賦給e
	for (++elem; elem <= tail; elem++)			//被刪除元素之後的元素左移
	{
		*(elem - 1) = *elem;
	}
	--sqList.length;							//表長減1
	return OK;
}
  • 遍歷方法
void ListShow(SqList sqList)
{
	int length = sqList.length;
	int listsize = sqList.listsize;
	cout << "length:" << length << "\tlistsize:" << listsize << endl;
	for (int i = 0; i < length; i++)
	{
		cout << sqList.elem[i] <<"\t";
	}
	cout << endl;
}
  • 測試方法
int main()
{
	SqList sqList;
	InitList(sqList);
	for (int i = 1; i <= 100; i++)
	{
		ListInsert(sqList, i, i);
	}
	ListInsert(sqList, 10, 11);
	ListShow(sqList);
	system("pause");
	return OK;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章