順序表

 


順序表是利用數組來實現的線性結構,主要是能執行一些插入和刪除的操作。

//A。h

#ifndef A_H
#define A_H
//#include<vector.h>
#include<iostream>
using namespace std;
const int MaxListSize=20;
template<typename T>
class SeqList
{
public:
	SeqList(T a[],int n=0);
	~SeqList();
	int Length();
	SeqList<T> & Insert(int i,T x);
	SeqList<T> & Delete(int i);
	T GetNode(int i);
	int LocateNode(T x);
	void ShowList();
	bool IsEmpty();
	bool IsFull();
private:
	T * data;
	int length;
};
#endif


 

A.CPP

#include"A.h"
//#include<iostream>
//using namespace std;
template<class T>
SeqList<T>::SeqList(T a[],int n)
{
T  * dt=new T[MaxListSize];
	data=dt;
	if(n>MaxListSize)
	{
		T * b=new T[2*MaxListSize];
		data=b;
	}
	for(int i=0;i<n;i++)
		data[i]=a[i];
	length=n;
}
template<class T>
SeqList<T>::~SeqList()
{
	length=0;
	T	 * s=data;
	int i=0;
	while(i!=length)
	{
		delete s;
	}
}
template<class T>
int SeqList<T>::Length()
{
	return length;
}
template<class T>
SeqList<T> & SeqList<T>::Insert(int i, T x)
{
	if(IsFull())
	{
		cout<<"存儲空間已滿,無法進行插入!"<<endl;
	}
	else
	{
	for(int k=length;k>i;k--)
		data[k]=data[k-1];
	data[i]=x;
	length++;
	}
	return *this;
}
template<class T>
SeqList<T> & SeqList<T>::Delete(int i)
{
	if(IsEmpty())
	{
		cout<<"順序表爲空!!!!,刪除錯誤!"<<endl;
		exit(0);
	}
	else
	{
	for(int j=i;j<length;j++)
		data[j]=data[j+1];
	length--;
	}
	return *this;
}
template<class T>
T SeqList<T>::GetNode(int i)
{
		return data[i];
}
template<class T>
int SeqList<T>::LocateNode(T x)
{	
	int f=-1;
	int i;
	for(i=0;i<length;i++)
	{
		if(data[i]==x)
		{
			f=i;
		}
	}
	return f;
}
template<class T>
void SeqList<T>::ShowList()
{
	for(int i=0;i<length;i++)
		cout<<data[i]<<"  ";
	cout<<endl;
}
template<class T>
bool SeqList<T>::IsEmpty()
{
	return length==0;
}
template<class T>
bool SeqList<T>::IsFull()
{
	return length==MaxListSize;
}


 

main。cpp

#include"A.h"
#include"A.cpp"
//#include<iostream>
//using namespace std;
void main()
{
	int a[10]={1,2,3,4,5,6,7,8,9,10};
	SeqList<int> sl(a,10);
	sl.ShowList();
	int x=11;
	sl.Insert(9,x);
	sl.ShowList();
	int k=sl.GetNode(9);
	if(k==11)
		cout<<"插入成功!"<<endl;
	else
		cout<<"插入失敗!"<<endl;
	k=sl.LocateNode(x);
		cout<<"x在順序表中是第"<<k<<"位"<<endl;
	sl.Delete(x);
	sl.ShowList();
	getchar();
}


 

 

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