顺序表的实现 呵呵,最近都不知道忙的什么,好几天没有更新了,过几天又有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) 改了好几次也不明白是哪儿的错误,希望高手指教,谢谢先:)
|