1. 程式人生 > >資料結構基礎知識(二)

資料結構基礎知識(二)

 順序表

1.線性表

線性表:是N(N>=0)個資料元素組成的有限序列k0,k1,...,kn-1。

線性表中的各個資料元素要求是同一種資料型別。資料元素相同的線性表又稱為陣列或向量。資料元素不同型別的線性表可通過建立索引表後,轉化為資料元素相同的線性表處理。

線性表的基本運算:

(1)表的初始化,即生成一個空表。

(2)判斷表是否為空,即表結點個數是否為0。

(3)判斷表是否已滿,即表結點個數是否為最大允許個數。

(4)求表長,即求表中結點個數。

(5)取表中第i個結點。

(6)查詢表中值為x的結點。

(7)在表中第i個位置上插入一個新的結點。

(8)刪除表中的第i個結點。

線性表的類的表示:

#include<iostream>
#include<string>

enum boolean{FALSE,TURE};
template<class T>

class LinearList     //申請線性表的一個類
{
	private:
	T *data;               //線性表以陣列形式存放
	int MaxSize;           //表空間最大範圍
	int Last;              //表長
	public:
	LinearList(int MaxSize = defaultSize);    
	~LinearList(void);
	boolean ListEmpty(void);
	boolean ListFull(void);
	int ListLength(void)const;
	T GetElem(int i);
	int LocateElem(T&x)const;
	int InsertElem(T&x,int i);
	int DeleteElem(int i);
};

template<class T>
LinearList<T>::LinearList(int sz)
{
	if(sz>0)
	{
		MaxSize=sz;
		Last=0;
		data=new T[MaxSize];   //建立表空間
	}
}

template<class T>
LinearList<T>::~LinearList(void)
{
delete[]data;

}
template<class T>
boolean LinearList<T>::ListEmpty(void)  //判斷線性表是否為空
{
return(Last>=MaxSize)?TRUE:FALSE;
}

template<class T>
boolean LinearList::ListLength(void)const    //求線性表的長度
{
return Last;
}
	
template<class T>
T LinearList<T>::GetElem(int i)   //求線性表中的結點的值
{
	return(i<0||i>Last)?NULL:data[i];
}

template<class T>
int LinearList<T>::LocateElem(T&x)const
{
	for(int i=0;i<Last;i++)
		if(data[i]==x)return i;
	    return -1;
}

template <class T>
boolean LinearList<T>::InsertElem(T&x,int i)  //插入值為x的結點
{
	if(i<0||i>Last==MaxSize)
		return FALSE;
	else
	{
		for(int j=Last;j>i;j--)
			data[j]=data[j-1];
		data[i]=x;
		Last++;
		return TRUE;
	}
}

template <class T>
boolean LinearList<T>::DeleteElem(int i)   //刪除線性表第i個結點
{
	if(i<0||i>Last||Last==0)
		return FALSE;
	else
	{
		for(int j=i;j<Last-1;j++)data[j]=data[j+1];
		Last--;
		return TRUE;
	}
}