数据结构(C语言版)严蔚敏 吴伟民
线性表(静态链表)ADT结构及相关函数
环境:Linux Ubuntu(云服务器)
工具:vim
代码块(头文件,函数文件,主文件)
slinklist.h头文件
#ifndef _SLINKLIST_H
#define _SLINKLIST_H
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define NOEXIST -3
#define DATAFMT "%d"
typedef int Status;
typedef int ElemType;
#define MAXSIZE 1000
typedef struct {
ElemType data;
int cur;
}component, SLinkList[MAXSIZE];
void InitSpace_SL(SLinkList &space);
int Malloc_SL(SLinkList &space);
void Free_SL(SLinkList &space, int k);
void difference(SLinkList &space, int &S);
Status visit(ElemType e);
Status ListTraverse_L(SLinkList &space, Status visit(ElemType));
#endif
slinklist.c函数文件
#include <stdio.h>
#include <stdlib.h>
#include "slinklist.h"
void InitSpace_SL(SLinkList &space) {
int i;
for(i = 0; i < MAXSIZE - 1; ++i) {
space[i].cur = i + 1;
}
space[MAXSIZE-1].cur = 0;
}
int Malloc_SL(SLinkList &space) {
int i = space[0].cur;
if(space[0].cur) {
space[0].cur = space[i].cur;
}
return i;
}
void Free_SL(SLinkList &space, int k) {
space[k].cur = space[0].cur;
space[0].cur = k;
}
void difference(SLinkList &space, int &S) {
InitSpace_SL(space);
int m, n;
printf("Enter the length of SLinkList A & B: ");
scanf("%d %d", &m, &n);
int i, j;
S = Malloc_SL(space);
int r = S;
for(j = 1; j <= m; ++j) {
i = Malloc_SL(space);
printf("Enter No.%d node data: ", i - 1);
scanf(DATAFMT, &space[i].data);
space[r].cur = i;
r = i;
}
space[r].cur = 0;
ElemType b;
int k, p;
for(j = 1; j <= n; ++j) {
printf("Enter No.%d node data: ", j);
scanf(DATAFMT, &b);
p = S;
k = space[S].cur;
while(k != space[r].cur && space[k].data != b) {
p = k;
k = space[k].cur;
}
if(k == space[r].cur) {
i = Malloc_SL(space);
space[i].data = b;
space[i].cur = space[r].cur;
space[r].cur = i;
}
else {
space[p].cur = space[k].cur;
Free_SL(space, k);
if (r == k) r = p;
}
}
}
Status visit(ElemType e) {
printf(DATAFMT, e);
printf(" ");
return OK;
}
Status ListTraverse_L(SLinkList &space, Status visit(ElemType)) {
printf("List traverse: ");
int i;
for(i = space[1].cur; i != 0; i = space[i].cur) {
if(!visit(space[i].data)) {
return FALSE;
}
}
printf("\n");
return OK;
}
main.c主文件
#include <stdio.h>
#include <stdlib.h>
#include "slinklist.h"
#include "slinklist.c"
int main() {
SLinkList space;
int num = 0;
difference(space, num);
ListTraverse_L(space, visit);
return 0;
}
运行结果显示如下:
