实现堆栈的先进后出
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 10
#define Error 0
#define True 1
typedef struct
{
int id;
char *name;
}ElemtType;
//定义栈的结构
ElemtType p1 = {12,"qwe"};
ElemtType p2 = {23,"her"};
ElemtType p3 = {34,"sss"};
ElemtType p4 = {67,"aag"};
typedef struct Seqstack
{
ElemtType elem[MAX_SIZE];//存放数据元素的数组
int top;//栈顶
int length;//当前栈的长度
}Seqstack;
//栈的初始化
void initseqstack(Seqstack* stack)
{
stack->top = -1;
stack->length = 0;
}
//入栈操作
int pushseqstack(Seqstack* stack,ElemtType elem)
{
if(stack->top==MAX_SIZE-1)
{
printf("满栈\n");
return Error;
}
stack->top++;//加入新的元素
stack->elem[stack->top] = elem;//江元素赋值给栈顶
stack->length++;
return True;
}
//出栈
int popseqstack(Seqstack* stack,ElemtType* elem)
{
if(stack->top==-1)
{
printf("栈为空\n");
return 0;
}
//出栈要把元素输出,返回栈顶
* elem = stack->elem[stack->top];
stack->top--;
stack->length--;
return True;
// free(stack->elem[stack->top]);
}
/****************
*函数说明:清空栈
*
****************/
void Clearstack(Seqstack* stack)
{
stack->top = -1;
stack->length = 0;
}
/***********************
*函数说明:栈是否为空
*
*************************/
void Emptyorstack(Seqstack* stack)
{
if(stack->top ==-1)
{
printf("栈顶为空\n");
}
}
void printstack(Seqstack* stack)
{
int i = 0;
ElemtType elem;
for(i = 0;i<stack->length;i++)
{
printf("name:%s id:%d\n",stack->elem[i].name,stack->elem[i].id);
}
}
/***********************
*函数说明:返回栈顶元素
*
*************************/
int main()
{
Seqstack stack;
ElemtType* elem = (ElemtType*)malloc(sizeof(ElemtType*));
initseqstack(&stack);
pushseqstack(&stack,p1);
pushseqstack(&stack,p2);
printstack(&stack);
printf("---------------------\n");
popseqstack(&stack,elem);
printstack(&stack);
return 0;
}
实现展示
先进入的是12,然后23,出栈一次后,剩下的是12