C++数据结构之静态链表
希望大家可以给出宝贵意见。
#pragma once
#ifndef SLIST_H
#define SLIST_H
#define MAXSIZE 1000
#include
#include
using namespace std;
template
class SList
{
public:
typedef struct
{
T data;
int cur;
}Node;
SList();
~SList();
bool Insert(const T& e, int index);
bool Delete(T& e, int index);
vector Out() const;
private:
int NewSpace();
void DeleteSpace(int index);
bool Empty()const;
bool Full()const;
Node slist[MAXSIZE];
int length;
};
template
SList::SList() :length(0)
{
for (int i = 0; i < MAXSIZE - 1; i++)
{
slist[i].cur = i + 1;
}
slist[MAXSIZE - 1].cur = 0;
}
template
SList::~SList()
{
}
template
int SList::NewSpace()
{
int i = slist[0].cur;
if (slist[0].cur)
{
slist[0].cur = slist[i].cur;
}
return i;
}
template
void SList::DeleteSpace(int index)
{
slist[index].cur = slist[0].cur;
slist[0].cur = index;
}
template
bool SList::Empty()const
{
return length == 0;
}
template
bool SList::Full()const
{
return length == MAXSIZE - 2 ? true : false;
}
template
bool SList::Insert(const T& e, int index)
{
if (Full())
{
cout << “静态链表已满!” << endl;
return false;
}
if (index<1 || index>length + 1)
{
cout << “插入的位置有误!” << endl;
return false;
}
int k = NewSpace();
int j = MAXSIZE - 1;
slist[k].data = e;
for (int i = 0; i < index - 1; i++)
{
j = slist[j].cur;
}
slist[k].cur = slist[j].cur;
slist[j].cur = k;
++length;
return true;
}
template
bool SList::Delete(T& e, int index)
{
if (Empty())
{
cout << “静态链表已空!” << endl;
return false;
}
if (index<1 || index>length)
{
cout << “删除位置有误!” << endl;
return false;
}
int j = MAXSIZE - 1;
for (int i = 0; i < index - 1; i++)
{
j = slist[j].cur;
}
int k = slist[j].cur;
e = slist[k].data;
slist[j].cur = slist[k].cur;
DeleteSpace(k);
length–;
return true;
}
template
vector SList::Out()const
{
vector result;
int i = slist[MAXSIZE - 1].cur;
while (i != 0)
{
result.push_back(slist[i].data);
i = slist[i].cur;
}
return result;
}
#endif // !SLIST_H