虽然能遍历,但是会清空栈
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct{
int data[100];
int top;
}stack;
//初始化
stack* init(){
stack *s;
s=(stack*)malloc(sizeof(stack));
s->top=0;
return s;
}
//压栈
stack* push(stack *s,int val){
if(s->top==100){
printf("stack full\n");
return NULL;
}
printf("push %d into stack\n",val);
s->data[s->top++]=val;
return s;
}
//退栈
int pop(stack *s){
int get;
if(s->top==0){
printf("stack empty");
return NULL;
}
get=s->data[--s->top];
printf("pop %d from stack\n",get);
return get;
}
//遍历
void tra(stack *s){
stack *temp=s;
while(temp->top!=0){
int a;
a=temp->data[--temp->top];
printf(" %d ",a);
}
printf("\n");
}
int main(){
stack *s=init();
push(s,1);
push(s,2);
push(s,3);
pop(s);
tra(s);
return 0;
}