输入若干个整数(不超过1000),依次入栈;scanf("%d",&e)==1来作为输入判断
依次出栈并输出元素值,以空格分隔。
#include <stdio.h>
//元素elem进栈
int push(int* a,int top,int elem){
a[++top]=elem;
return top;
}
//数据元素出栈
int pop(int * a,int top){
if (top==-1) {
printf("空栈");
return -1;
}
printf("%d ",a[top]);
top--;
return top;
}
int main() {
int a[1000];
int top=-1;
int e,count=0;
while(scanf("%d",&e)==1){
top=push(a, top,e);
count++;
}
for(int i=0;i<count;i++){
top=pop(a, top);
}
return 0;
}
定义1000个元素的数组,入栈索引从小到大,出栈索引只允许从大到小。
#include <stdio.h>
#define ROOM 1005
typedef struct stack
{
int space[ROOM];
int top;
} Stack;
int pop(Stack *s)
{
if (s->top >= 0)
{
printf("%d ", s->space[s->top]);
s->top--;
return 1;
}
return 0;
}
int push(Stack *s, int e)
{
if (s->top < ROOM - 1)
{
s->top++;
s->space[s->top] = e;
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
Stack s;
s.top = -1;
int e;
while (scanf("%d", &e) == 1 && push(&s, e))
;
while (pop(&s))
;
return 0;
}
栈:先进后出,用链表来做,就是头插法,后进入的在前面,出栈的时候从链表头取。