//
更多原创“uC/OS-II学习笔记之:系列”基础及嵌入式相关知识详解,请访问可乐虎博客:
相信不会让您失望!! //
//写篇顺序栈,与大家共勉!
//不足错误之处,望指教!
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 5
typedef int ElementType;
//定义结构体
typedef struct SeqStack
{
ElementType array[STACK_SIZE];
ElementType top;
}SEQSTACK;
//初始化顺序栈
bool InitStack(SEQSTACK *pS)
{
if (!pS)//内存分配失败
{
return FALSE;
}
pS->top = -1;
return TRUE;
}
//判断是否为空
bool IsEmpty(SEQSTACK *pS)
{
if (pS->top < 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
//判断是否为满
bool IsFull(SEQSTACK *pS)
{
if (pS->top == STACK_SIZE-1)
{
return TRUE;
}
else
{
return FALSE;
}
}
//压栈(入栈)
bool PushStack(SEQSTACK *pS, ElementType element)
{
if (IsFull(pS))
{
return FALSE;
}
pS->top++;
pS->array[pS->top] = element;
return TRUE;
}
//出栈
ElementType PopStack(SEQSTACK *pS)
{
ElementType element;
if (IsEmpty(pS))
{
return FALSE;
}
element = pS->array[pS->top];
pS->top--;
printf("element=%d\n", element);
return element;
}
//获取栈顶元素
ElementType GetTop(SEQSTACK *pS)
{
ElementType element;
if (IsEmpty(pS))
{
return FALSE;
}
element = pS->array[pS->top];
printf("element=%d\n", element);
return element;
}
//置空顺序栈
void SetEmpty(SEQSTACK *pS)
{
pS->top = -1;
return;
}
//遍历顺序栈
bool TraStack(SEQSTACK *pS)
{
ElementType element;
if (IsEmpty(pS))
{
return FALSE;
}
while (pS->top > -1)
{
element = pS->array[pS->top];
pS->top--;
printf("element=%d\n", element);
}
return TRUE;
}
//主函数
int main(void)
{
SEQSTACK *pS;//定义一个指向结构体变量的指针
pS = (SEQSTACK *)malloc(sizeof(SEQSTACK));
//下面函数的参数使用p和&pS是等效的
InitStack(pS);//初始化
PushStack(pS, 1);//压栈
PushStack(pS, 2);
PushStack(pS, 3);
PushStack(pS, 4);
PushStack(pS, 5);
GetTop(pS);//取栈顶元素
printf("\n");
PopStack(pS);//出栈
printf("\n");
TraStack(pS);//遍历栈
free(pS);//释放pS所占内存空间
return 0;
}