数组栈,在数组顺序表的基础上,融合栈 头进尾出的特点,即只可以尾插尾删;另外,需要top一个结构体成员来记录栈顶位置,取栈顶元素和插、删数据!
Stack.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct stack {
int* p;
int capacity;
int top;
}StackNode;
void InitStack(StackNode* head);
void StackPush(StackNode* head, int x);
void StackPop(StackNode* head);
int StackTop(StackNode* head);
bool Emp(StackNode* head);
void Display(StackNode* head);
void Destory(StackNode* head);
Stack.c
#include"stack.h"
void InitStack(StackNode* head) {
head->p = malloc(sizeof(StackNode)*4);
if (head->p == NULL) {
printf("malloc init failed \n");
exit(-1);
}
head->top = 0;
head->capacity = 5;
}
void StackPush(StackNode* head, int x) {
assert(head);
if (head->top == head->capacity)
{
StackNode* tmp = malloc(sizeof(StackNode) * head->capacity * 2);
if (tmp == NULL)
{
return printf("malloc failed\n");
exit(-1);
}
else
{
head->p = tmp;
head->capacity *= 2;
}
}
head->p[head->top] = x;
head->top++;
}
void StackPop(StackNode* head) {
assert(head);
assert(head->top > 0);
head->top--;
}
int StackTop(StackNode* head) {
assert(head);
return head->p[head->top-1];
}
bool Emp(StackNode* head) {
assert(head);
return head->top == 0;
}
void Display(StackNode* head) {
assert(head);
StackNode* cur = head;
for (size_t i = 0; i < head->top; i++)
{
printf("%d,",cur->p[i]);
}
printf("\n");
}
void Destory(StackNode* head) {
free(head->p);
head->p == NULL;
head->top = head->capacity = 0;
}
main.c
#include"stack.h"
void main() {
StackNode s;
InitStack(&s);
StackPush(&s, 1);
StackPush(&s, 2);
StackPush(&s, 3);
Display(&s);
StackPop(&s,3);
StackPop(&s, 2);
Display(&s);
int res = StackTop(&s);
printf("栈顶元素为:%d \n",res);
bool b = Emp(&s);
printf("%d",b);
Destory(&s);
}
结果:
|