//stack的数组实现(方法类似于类的定义)
//1:实现栈的数据定义
//2:实现操作方法的定义push pop empty full top(并不需要,因为stack[top]就是top)
//1:实现栈的数据定义
//2:实现操作方法的定义push pop empty full top(并不需要,因为stack[top]就是top)
//ps:在采用数组实现栈时,数组0下标对应的是栈底,top下标对应的是栈顶
#include <stdio.h>
#define MAXSIZE 100
struct node{
int a;
char b;
};
//1的实现
struct stack{
node n[MAXSIZE];//这里定义n[0]为栈底
int top;
};
//2的实现
bool emptyStack(stack *s)
{
if(s->top==-1)
return true;
return false;
}
bool fullStack(stack *s)
{
if(s->top==MAXSIZE-1)
return true;
return false;
}
bool pushStack(stack *s ,node p)
{
if(fullStack(s))
return 0;
s->top++;
s->n[s->top]=p;
return 1;
}
bool popStack(stack *s)
{
if(emptyStack(s))
return false;
s->top--;
return true;
}
void main()
{
stack s;
s.top=-1;
node a={1,'f'};
node b={2,'e'};
node c={3,'g'};
pushStack(&s,a);
pushStack(&s,b);
pushStack(&s,c);
printf("%2d\n",s.n[0].a);
printf("%2d\n",s.n[1].a);
printf("%2d\n",s.n[s.top].a);
popStack(&s);
printf("%2d\n",s.n[s.top].a);
}

本文介绍如何使用数组实现栈的基本操作,包括定义栈的数据结构、判断栈是否为空或满的方法、入栈(push)与出栈(pop)操作的具体实现,并提供了一个简单的示例程序。
311

被折叠的 条评论
为什么被折叠?



