逍遥进阶八阵还是诛仙:进栈、出栈的C++实现过程程序:

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/29 09:32:34

#include<iostream.h>
class STACK{
private:
int base[100];
public:
int size;
STACK(){size=0;};
void push(int a)//入栈
{
base[size++]=a;
}
int pop()//出栈
{
return base[--size];
}
};
int main()
{
STACK s;
s.push(3);
s.push(4);
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
system("pause");
}

/*此例主要理会建栈和地址传递(y)的应用*/
#include<stdio.h>
typedef struct stack_node{
char data;
struct stack_node *next;
}SLnode;/*栈结点结构*/
typedef struct {
SLnode *top;
}LS;/*栈顶指针*/
void InitStack(LS *s)/*建空栈*/
{
s->top=NULL;
}
void Push(LS *s,char x)/*入栈*/
{
SLnode *p;
p=(SLnode *)malloc(sizeof(SLnode));/*结点空间生成*/
p->data=x;
p->next=s->top;/*指针指向*/
s->top=p;
}
char pop(LS *s,char *y)
{ SLnode *p;
*y=s->top->data;/*通过地址传递得到栈顶元素值*/
p=s->top;
s->top=p->next;/*修改栈顶指针*/
free(p);/*释放空间*/
}
void main()
{
LS *s;char y;
s=(LS *)malloc(sizeof(LS));
/*s的定义也可以用 LS s;然后赋予下面的各个函数以&s;如果这样则&s也是LS*型的地址*/
InitStack(s);
Push(s,'a');
Push(s,'b');
Push(s,'e');
pop(s,&y);
printf("%c",y);
}