一、栈的概念及结构
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。 出栈:栈的删除操作叫做出栈。出数据也在栈顶。
二、栈的实现
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。
2.1、初始化栈与栈的销毁
void StackInit(Stack* ps)
{
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
2.2、入栈与出栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (Stack*)realloc(ps->a ,sizeof(STDataType)* newcapacity);
if (tmp == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = data;
ps->top++;
}
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->top>0);
ps->top--;
}
2.3、取栈顶
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty (ps));
return ps->a[ps->top - 1];
}
2.4、检测栈是否为空,如果为空返回非零结果,如果不为空返回0与获取栈中有效元素个数
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
三、总代码块
3.1、Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackDestroy(Stack* ps);
void StackPush(Stack* ps, STDataType data);
void StackPop(Stack* ps);
STDataType StackTop(Stack* ps);
bool StackEmpty(Stack* ps);
int StackSize(Stack* ps);
3.2、Stack.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
void StackInit(Stack* ps)
{
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (Stack*)realloc(ps->a ,sizeof(STDataType)* newcapacity);
if (tmp == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = data;
ps->top++;
}
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->top>0);
ps->top--;
}
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty (ps));
return ps->a[ps->top - 1];
}
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
3.3、Tast.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
TestStack1()
{
Stack ps;
StackInit(&ps);
StackPush(&ps,1);
StackPush(&ps,2);
StackPush(&ps,3);
StackPop(&ps);
printf("%d \n", StackTop(&ps));
StackPush(&ps,4);
StackPush(&ps,5);
printf("%d\n", StackSize(&ps));
while (!StackEmpty(&ps))
{
printf("%d ", StackTop(&ps));
StackPop(&ps);
}
StackDestroy(&ps);
}
TestStack2()
{
char s[] = { '(',']' };
isValid(s);
}
int main()
{
TestStack2();
return 0;
}
|