使用数组模拟顺序栈。栈底为数组的首地址,栈顶为数组的尾地址,因为数组中尾插不需要一个一个移动数据,相比头插效率更高。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1024
//定义顺序栈的结构体
struct SStack {
void* data[MAX];
int m_size;
};
typedef void* seqStack;
//初始化栈
seqStack init_SStack() {
//给栈开辟空间
struct SStack* myStack = malloc(sizeof(struct SStack));
if (myStack == NULL)
return NULL;
//对栈结构体内属性进行初始化
myStack->m_size = 0;
memset(myStack->data, 0, sizeof(void*) * MAX);
return myStack;
}
//入栈(本质就是对数组的尾插)
void push_Stack(seqStack stack, void * data) {
if (stack == NULL || data == NULL)
return;
//判断栈是否已经满
struct SStack* myStack = stack;
if (myStack->m_size == MAX)
return;
//对数组进行尾插
myStack->data[myStack->m_size] = data;
//更新栈长度
myStack->m_size++;
}
//出栈(本质就是数组的尾删)
void pop_SStack(seqStack stack) {
if (stack == NULL)
return;
//如果数组内还有元素 进行return
struct SStack* myStack = stack;
if (myStack->m_size == 0)
return;
//数组的尾删就是将数组内的最后一个元素置为空即可
myStack->data[myStack->m_size - 1] = NULL;
//更新数组长度
myStack->m_size--;
}
//返回栈顶元素
void* get_topValue(seqStack stack) {
if (stack == NULL)
return NULL;
struct SStack* myStack = stack;
if (myStack->m_size == 0)
return NULL;
return myStack->data[myStack->m_size - 1];
}
//返回栈的大小
int size_SStack(seqStack stack) {
if (stack == NULL)
return -1;
struct SStack* myStack = stack;
return myStack->m_size;
}
//判断栈是否为空 栈为空时返回真,非空返回假
int isEmpty_SStack(seqStack stack) {
if (stack == NULL)
return -1;
struct SStack* myStack = stack;
if (myStack->m_size == 0)
return 1;
return 0;
}
//销毁栈
void destroy_SStack(seqStack stack) {
if (stack == NULL)
return;
free(stack);
stack = NULL;
}
//测试
typedef struct Person {
char name[64];
int age;
}Person;
void test() {
Person p1 = { "bobo",23 };
Person p2 = { "toto",24 };
Person p3 = { "gogo",25 };
Person p4 = { "yoyo",26 };
//初始化一个栈
seqStack myStack = init_SStack();
//入栈
push_Stack(myStack, &p1);
push_Stack(myStack, &p2);
push_Stack(myStack, &p3);
push_Stack(myStack, &p4);
//返回栈顶元素
Person *p = get_topValue(myStack);
printf("%s,%d\n", p->name, p->age);
//出栈一个
pop_SStack(myStack);
p = get_topValue(myStack);
printf("%s,%d\n", p->name, p->age);
//返回栈的大小
int ret = size_SStack(myStack);
printf("栈的大小为:%d\n", ret);
//测试栈是否为空
if (!isEmpty_SStack(myStack)) {
printf("栈内有元素\n");
}
//销毁栈
destroy_SStack(myStack);
myStack = NULL;
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}