//静态链表:非空闲链表+空闲链表,长度固定
//数据结构:节点数据+下标(下一个节点的索引)
//SL[0]存储备用链表的第一个节点下标cur,SL[MAXSIZE-1]存储有效链表的第一个节点下标cur
//初始化:每个节点的cur为后一个节点下标,第一个空闲节点下标 SL[0].cur = 1
//第一个有效节点的下标 SL[MAXSIZE-1].cur = 0
#pragma once
#include <iostream>
#define MAXSIZE 100
using namespace std;
template <typename T>
class CStaticList
{
public:
typedef struct{
T date;
int cur;
}Node;
CStaticList(){};
~CStaticList(){};
bool Insert(const T &e, int index = 1){
if (isFull()){
cout << "Can't insert element to a full List!\n";
return false;
}
if (index < 1 || index > Length + 1){ // 1 <= index <= Length
cout << "The invalid index!\n";
return false;
}
int k = NewSpace();
int j = MAXSIZE - 1;
if (k){ // 如果第一个空闲节点不为0
SL[k].data = e;
for (int i = 1; i <= index - 1; i++){
j = SL[j].cur; // 遍历前index-1个有效节点,获得第index个节点的前一个节点的下标
}
SL[k].cur = SL[j].cur;//第k个节点的下一个节点的为j的下一个节点
SL[j].cur = k; //j的下一个节点索引为k
++Length;
return true;
}
return false;
}
bool Delete(T &e, int index = 1){
//第index-1位的节点的下一个指向index+1位,SL[0].cur 指向index
if (isEmpty()){
cout << "Can't delete element in an empty List!\n";
return false;
}
if (index < 1 || index > Length + 1){ // 1 <= index <= Length
cout << "The invalid index!\n";
return false;
}
int j = MAXSIZE - 1;
int i = 1;
for (; i <= index - 1; i++){
j = SL[j].cur;
}
i = SL[j].cur; // i 为第index个节点的下标, j为第index-1个节点的下标
SL[j].cur = SL[i].cur;
e = SL[i].data;
DeleteSpace(i);
--Length;
return true;
}
void Show()const{
if (isEmpty()){
cout << "The list is empty!\n";
return;
}
int k = SL[MAXSIZE - 1].cur;
for (int i = 1; i <= Length; i++){
cout << SL[k].data << " ";
k = SL[k].cur;
}
cout << endl;
}
private:
Node SL[MAXSIZE];
int Length;
int NewSpace(){ //返回list中一个可以用的空闲下标,并更新首位空闲节点下标
int i = SL[0].cur;
if (i) //如果节点i可用
SL[0].cur = SL[i].cur; //设置i的下一个节点为空闲节点
return i;
}
void DeleteSpace(int index){ //删除list中的index元素
SL[index].cur = SL[0].cur; //将要删除的节点加入到空闲节点最前
SL[0].cur = index; //将index设置为空闲节点
}
bool isEmpty()const{
return Length == 0;
}
bool isFull()const{
if (Length > MAXSIZE - 2)
return true;
return false;
}
};
静态链表
最新推荐文章于 2023-11-04 20:00:22 发布