數據結構+C++_№5

順序表的實現

  呵呵,最近都不知道忙的什麼,好幾天沒有更新了,過幾天又有N多事情,看來又得向後拖了:),程序到是寫了,就是沒時間往Blog上帖了:)

這個是抽象數據定義:

/*第2章 數組 第2.2節順序表
*第42頁 抽象數據定義
*
* 2005年6月13號,星期一晚
* -----------by Speed1
*/
#ifndef SEQLIST_H
#define SEQLIST_H
const DefaultSize=20;
template< class Type> class SeqList
{
 public:
  SeqList(int MaxSize=DefaultSize);	//構造函數
  ~SeqList() {delete []data; }	//析構函數
  int Lenght() const {return last+1;}	//計算表長度
  int Find(Type& x) const;	//定位函數:找x在表中的位置
  int IsIn(Type& x);	//判斷x是否在表中
  int Insert(Type& x ,int i);	//插入x在表中第i個位置處
  int Remove(Type& x);	//刪除x
  int Next(Type& x);	//尋找x的後繼
  int Prior(Type& x);	//尋找x的前驅
  int IsEmpty() {return last==-1;}	//判斷順序表是否爲空,空則返回1;否則返回0
  int IsFull() {return last==MaxSize-1;}	//判斷順序表滿否,滿則返回1;否則拜賀0
  Type Get(int i) {return i<0||i>last?NULL:data[i];}	//取第i個元素的值
 private:
  Type* data;	//存放順序表的數組
  int MaxSize;	//順序表最大可容納項數
  int last;	//順序表當前是已存表項的最後位置
  };
  #endif
 
這個是抽象順序表的實現:

/*第2章 數組 第2.2節順序表
*第42頁 抽象順序表實現
*
* 2005年6月13號,星期一晚
* -----------by Speed1
*/
#include <iostream.h>
#include "SeqList.h"
template <class Type> SeqList<Type>::SeqList(int sz)
{
	//構造函數,通過描寫參數sz定義數組的長度。
	if(sz>0)
	{
		MaxSize=sz;
		last=-1;
		data=new Type[MaxSize];
	}
}
template <class Type> int SeqList<Type>::Find(Type& x) const
{
//定位,找x在表中位置 ,若查找成功,函數 返回表項的位置,否則函數返回-1
int i=0;
while(i<=last&&data[i]!=x)
		i++;
if(i>last)
		return -1;
else
		return i;
}
template <class Type> int SeqList<Type>::IsIn(Type& x)
{
//判斷x是否在表中
int i=0,found=0;
while(i<==last&&!found)
	if(data[i]!=x)
		i++;
	else
		found=1;
return found;
}
template <class Type> int SeqList<Type>::Insert(Type& x,int i)
{
	//插入x在表中第i個位置處。函數返回插入是否成功的信息,若爲0則插入不成功。
	if(i<0||i>last+1||last==MaxSize-1) return 0;
	else
	{
		last++;
		for(int j=last;j>i;j--)
		data[j]=data[j-1];
		data[i]=x;
		return 1;
	}
}
template <class Type> int SeqList<Type>::Remove(Type& x)
{
	int i=Find(x);
	if(i>=0)
	{
		last--;
		for(int j=i;j<=last;j++)
			data[j]=data[j+1];
		return 1;
	}
return 0;
}
template <class Type> int SeqList<Type>::Next(Type& x)
{
  //尋找x的後繼數據
  int i=Find(x);
  if(i>=0&&i<last)
  	return i+1;
  else 
 	 return -1;
}
template <class Type> int SeqList<Type>::Prior(Type& x)
{
  int i=Find(x);
  if(i>0&&i<=last)
  	return i-1;
  else 
  	return -1;
}

這個就是自己寫的測試主程序了:)


/*第2章 數組 第2.2節順序表
*第42頁 測試主程序
*
* 2005年6月13號,星期一晚
* -----------by Speed1
*/
#include <iostream.h>
#include "SeqList.h"
	//const defaultSize=20;
void main()
{
	SeqList<int> Test1(5);
	cout<<Test1.Lenght();
}

  也不知道怎麼回事,編譯沒有事,一鏈接運行就出錯,很奇怪的錯誤:|

Linking...
  link: executing 'E:/PROGRA~1/MICROS~1/VC98/Bin/link.exe'
  DS_Cpp_P42.obj : error LNK2001: unresolved external symbol "public: __thiscall
SeqList<int>::SeqList<int>(int)" (??0?$SeqList@H@@QAE@H@Z)
Debug/DS_Cpp_P42.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. DS_Cpp_P42.exe - 2 error(s), 0 warning(s)
  改了好幾次也不明白是哪兒的錯誤,希望高手指教,謝謝先:)

發佈了41 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章