#include <iostream>
#include <stdlib.h>
using namespace std;
//element of array
typedef int ListItem;
typedef struct snode *link;
typedef struct snode {
ListItem element;
int next; // point the index of next element.
} Snode;
//space
typedef struct space *Space;
typedef struct space {
int num,first; // [num] is the size of space. [first] is the index of first free element.
link node; //allocated array.
} Simul;
//List
typedef struct slist *List;
typedef struct slist{
int first; // the cursor of head list.
Space s;// free space.
}listNode;
//init the mock array space.
Space SpaceInit(int max){
int i;
Space s = (Space)malloc(sizeof(Simul));
s->num = max;
s->node = (link)malloc(max*sizeof(Snode));
for(i = 0;i<max-1;i++){
s->node[i].next = i+1; //initialize the chain of free elements.
}
s->node[i].next = -1; //set final element to -1.
s->first = 0; //set first element to 0.
return s;
}
//Allocate element.
int SpaceAllocate(Space s){
int i;
i = s->first; // get the index of first free element.
s->first = s->node[i].next; // set the [first] to point the index of next node in the chain.
return i;
}
//free element of array
void SpaceDeallocate(int i, Space s){
//save the [first] and set the new [first] to [i].
s->node[i].next = s->first;
s->first = i;
}
//initialize the list
List ListInit(int size, List L){
List list = (List)malloc(sizeof(listNode));
list->s = SpaceInit(size);
list->first = -1; // set the cursor to -1.
return L;
}
//get length of list
int ListLength(List L){
int i, len;
i = L->first;
len = 0;
// search the node until the next equals -1.
while(i != -1){
len++;
i = L->s->node[i].next;
}
return len;
}
//search the Kth element.
ListItem ListRetrieve(int k,List L){
int p = L->first;
for(int i = 1;i<k;i++){
p = L->s->node[p].next;
}
return L->s->node[p].element;
}
//locate the index of element
int Listlocate(ListItem x, List L){
int p = L->first;// p point the index of first element.
for(int i = 0;p != -1;i++){
if(L->s->node[p].element == x){
break;
}
p = L->s->node[p].next;
}
if(p == -1){
exit(1);
}
return p;
}
//Insert a element
void ListInsert(int k, ListItem x, List L){
int p,y,i;
if(k <0){
cout<<"out of bounds"<<endl;
exit(1);
}
p = L->first;
for(i = 1;i<k&&p != -1;i++){
p = L->s->node[p].next;
}
y = SpaceAllocate(L->s);
L->s->node[y].element = x;
if(k){
L->s->node[y].next = L->s->node[p].next;
L->s->node[p].next = y;
}else{
L->s->node[y].next = L->first;
L->first = y;
}
}
//Delete a element
ListItem ListDelete(int k,List L){
int p,q,i;
ListItem x;
if(k <1 || L->first == -1){
cout<<"out of bound"<<endl;
exit(1);
}
p = L->first;
if(k == 1){
L->first = L->s->node[p].next;
}else{
q = p;
for(i = 1;i<k-1 && q!=-1;i++){
q = L->s->node[q].next;
}
p = L->s->node[q].next;
L->s->node[q].next = L->s->node[p].next;
}
x = L->s->node[p].element;
SpaceDeallocate(p, L->s);
return x;
}
void PrintList(List L){
int p;
for(p = L->first;p != -1;p = L->s->node[p].next){
cout<<L->s->node[p].element<<endl;
}
}
int main(){
return 0;
}