静态链表

//静态链表:非空闲链表+空闲链表,长度固定
//数据结构:节点数据+下标(下一个节点的索引)
//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;
	}
	
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值