之前通过数组实现的,现在用结构体数组实现的,关键是结构体数组,然后写好分配及回收算法就行了
//结构体数组
typedef struct {
int data;
int cur;
}component,slink[MAXSIZE];
/*
* newlink.c
*
* Created on: 2017-9-29
* Author: Administrator
*/
#include <stdio.h>
#include<stdlib.h>
#include "testhead.h"
/*
* 通过定义结构体数组 来实现链表结构
*
*/
void test2() {
slink s; //结构体数组定义 。。 这里直接是1000个结构体了
initLink(s);
int i = malloc_s(s);
s[i].data = 0;
s[i].cur = 0;
add_s(i, 1, s);
add_s(i, 2, s);
add_s(i, 3, s);
add_s(i, 4, s);
add_s(i, 5, s);
pop_s(i,s);
show_s(i, s);
}
// init the array to a big linklist
void initLink(slink link) {
int i;
for (i = 0; i < MAXSIZE - 1; i++) {
link[i].cur = i + 1;
}
link[MAXSIZE - 1].cur = 0;
}
// malloc the space to the used link ,return the location and remove from the back array
/*
* the back link first is 0 and if you want to malloc the location ,the first is 1
* and set the link[0].cur=link[1].cur; then you will have a node ,and the back link don't have that one
* and the free is the same way
*/
int malloc_s(slink link) {
int i = link[0].cur;
if (i == 0) {
return 0;
}
link[0].cur = link[i].cur;
return i;
}
//free the location,to make that location in the back link
void free_s(slink link, int s) {
link[s].cur = link[0].cur;
link[0].cur = s;
}
//add the node to the link
void add_s(int firs, int value, slink s) {
while (s[firs].cur != 0) {
firs = s[firs].cur;
}
int lo = malloc_s(s);
s[lo].data = value;
s[lo].cur = 0;
s[firs].cur = lo;
}
//show all the node of the link
void show_s(int fir, slink s) {
if (s[fir].cur != 0) {
printf("value is %d\n", s[fir].data);
show_s(s[fir].cur, s);
} else {
printf("value is %d\n", s[fir].data);
}
}
//delete the last and return the last value
int pop_s(int fir, slink s) {
while (s[s[fir].cur].cur != 0) {
fir = s[fir].cur;
}
int value=s[s[fir].cur].data;
free_s(s,s[fir].cur);
s[fir].cur=0;
}
//insert the value by the index
int insert_s(int fir, slink s, int index, int val) {
int i;
if (index == 0) {
//insert at first
return 0;
}
for (i = 0; i < index - 1; i++) {
if (s[fir].cur != 0) {
fir = s[fir].cur;
} else {
return -1;
}
}
int x = malloc_s(s);
s[x].data = val;
s[x].cur = s[fir].cur;
s[fir].cur = x;
}
//delete by the value
int deleteValue(int fir, slink s, int value) {
if (s[fir].data == value) {
return value;
}
if (s[fir].cur == 0) {
return -1;
}
while (s[s[fir].cur].data != value) {
fir = s[fir].cur;
if (fir == 0) {
return -1;
}
}
int ss = s[s[fir].cur].cur;
free_s(s, s[fir].cur);
s[fir].cur = ss;
return value;
}