SList.h
#pragma once
#include<assert.h>
#include<iostream>
#include<fstream>
#define MAXSIZE 20
using namespace std;
typedef struct SNode {
int data;
int next;//静态链表的next并不是真的指针类型
}SNode, SLInkLIst[MAXSIZE];
void Init_SList(SLInkLIst s);
bool Insert_head(SLInkLIst s, int val);
bool Insert_tail(SNode * s, int val);//尾插
bool Is_Empty(SNode* s);//判空
bool is_Full(SNode* s);//判满
int GetLength(SNode *s);//获取数据结点的个数
int Search(SNode *s, int key);//在s查找第一个key值,找到返回结点地址下标,没有找到返回-1;
void Print_SList(SNode *s);//输出
bool DelVal(SNode* s, int val);//删除第一个val的值
void Clear(SNode * s);//清空数据
void Destroy(SNode *s);//销毁整个内存nm
SList.cpp
#define _CRT_SECURE_NO_WARNINGS
#include"SList.h"
#include<assert.h>
#include<iostream>
#include<fstream>
using namespace std;
void Init_SList(SLInkLIst s) {
assert(s != NULL);
s[0].next = 0;
for (int i = 1; i < MAXSIZE - 1; i++) {
s[i].next = i + 1;
}
s[MAXSIZE - 1].next = 1;
}
bool is_Full(SNode* s) {
assert(s != NULL);
return s[MAXSIZE - 1].next = 0;
}
bool Insert_head(SLInkLIst s, int val) {
assert(s != NULL);
if (is_Full(s)) return false;
int pos = s[1].next;
s[1].next = s[pos].next;
s[pos].data = val;
s[pos].next = s[0].next;
s[0].next = pos;
return true;;
}
void Print_SList(SNode* s) {//输出
assert(s != NULL);
if (s[0].next == 0) return;
int i = 0;
while (s[i].next != 0) {
cout << s[s[i].next].data << " ";
i = s[i].next;
}
cout << endl;
}
bool Insert_tail(SNode* s, int val) {//尾插
assert(s != NULL);
if (is_Full(s)) return false;
int pos = s[1].next;
s[1].next = s[pos].next;
s[pos].data = val;
int i;
for ( i = 0; i < MAXSIZE; i++) {
if (s[i].next == 0) {
break;
}
}
s[i].next = pos;
s[pos].next = 0;
return true;
}
bool Is_Empty(SNode* s) {//判空
assert(s != NULL);
return s[0].next == 0;
}
int GetLength(SNode* s) {//获取数据结点的个数
assert(s != NULL);
if (Is_Empty(s)) return 0;
int count = 0;
int i = 0;
while (s[i].next != 0) {
count++;
i = s[i].next;
}
return count;
}
//在s查找第一个key值,找到返回结点地址下标,没有找到返回-1;
int Search(SNode* s, int val) {
assert(s != NULL);
if (Is_Empty(s)) return -1;
int i = 0;
while (s[i].next != 0) {
if (s[s[i].next].data == val) return i;
i = s[i].next;
}
return -1;
}
bool DelVal(SNode* s, int val) {//删除第一个val的值
assert(s != NULL);
int i = 0;
bool tag = false;
while (s[i].next != 0) {
if (s[s[i].next].data == val) {
tag = true;
break;
}
i = s[i].next;
}
int j = s[i].next ;
while (s[s[j].next].next != 0) {
s[j].data = s[s[j].next].data;
j = s[j].next;
}
s[j].next = 0;
s[1].next =s[s[j].next].next;
return tag;
}
void Clear(SNode* s) {//清空数据
assert(s != NULL);
s[0].next = 0;
for (int i = 1; i < MAXSIZE-1; i++) {
s[i].next = i + 1;
}
s[MAXSIZE - 1].next = 1;
}
void Destroy(SNode* s) {//销毁整个内存nm
assert(s != NULL);
free(s);
s = NULL;
}
main.cpp
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include"SList.h"
using namespace std;
int main() {
SLInkLIst s;
Init_SList(s);
for (int i = 0; i < 10; i++) {
Insert_tail(s, i + 1);
}
Print_SList(s);
//int t = Search(s, 5);
DelVal(s, 5);
Print_SList(s);
}