游标实现链表

List_cursor.h
#ifndef LIST_CURSOR_H
#define LIST_CURSOR_H
constexpr auto MAX_SPACE = 10;;
#include <iostream>
using namespace std;
struct Node {
	int data;
	int next;
};
class List {
public:
	List();
	bool isEmpty();
	size_t Find(int);
	size_t FindPrevious(int);
	size_t Insert(int, int);
	size_t Erase(int);
	void show();
private:
	void InitializeCursorSpace();
	size_t CurrsorAlloc();
	void CurrsorFree(int);
	Node CursorSpace[MAX_SPACE];
};
#endif // !LIST_CURSOR_H

List_cursor.cpp
#include "List_cursor.h"
using namespace std;
List::List() {
	InitializeCursorSpace();
}

bool List::isEmpty() {
	return CursorSpace[0].next == 0;
}

size_t List::Find(int x) {
	if (!isEmpty()) {
		int temp = CursorSpace[0].next;
		while (temp && CursorSpace[temp].data != x)
			temp = CursorSpace[temp].next;
		return temp;
	}
	return -1;
}

size_t List::FindPrevious(int x) {
	if (!isEmpty()) {
		int pre = 1;
		int temp = CursorSpace[pre].next;
		while (temp && CursorSpace[temp].data != x) {
			pre = CursorSpace[pre].next;
			temp = CursorSpace[pre].next;
		}
		return pre;
	}
	return -1;
}

size_t List::Insert(int x, int p) {
	if (p != 0) {
		int temp = Find(p);
		int newNode = CurrsorAlloc();
		CursorSpace[newNode].data = x;
		CursorSpace[newNode].next = 0;
		CursorSpace[p].next = newNode;
		return newNode;
	}
	else {
		int newNode = CurrsorAlloc();
		CursorSpace[newNode].data = x;
		CursorSpace[newNode].next = 0;
		return newNode;
	}
}

size_t List::Erase(int x) {
	int pre = FindPrevious(x);
	int temp = CursorSpace[pre].next;
	CursorSpace[pre].next = CursorSpace[temp].next;
	CurrsorFree(temp);
	return pre;
}

void List::InitializeCursorSpace() {
	for (int i = 0; i != MAX_SPACE; ++i) {
		CursorSpace[i].data = 0;
		CursorSpace[i].next = i + 1;
		if (i == 9)
			CursorSpace[i].next = 0;
	}
}

size_t List::CurrsorAlloc() {
	int temp;
	temp = CursorSpace[0].next;
	CursorSpace[0].next = CursorSpace[temp].next;
	return temp;
}

void List::CurrsorFree(int p) {
	CursorSpace[p].data = 0;
	CursorSpace[p].next = CursorSpace[0].next;
	CursorSpace[0].next = p;
}

void List::show() {
	for (int i = 0; i != MAX_SPACE; ++i) {
		cout << i << " " << CursorSpace[i].data << " " << CursorSpace[i].next << endl;
	}
}
test.cpp
int main(int argc, char** argv) {
	List L;
	L.Insert(1, 0);
	L.Insert(2, 1);
	L.Erase(2);
	L.show();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值