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;
}