每日一题Day38

入栈和出栈的基本操作

描述

输入一个整数序列a1,a2,a3...,an。当ai不等于-1时将ai进栈;当ai=-1时,输出栈顶元素并将其出栈。

输入

多组数据,每组数据有两行,第一行为序列的长度n,第二行为n个整数,整数之间用空格分隔。当n=0时输入结束。

输出

对于每一组数据输出若干行。每行为相应的出栈元素。当出栈异常时,输出“POP ERROR”并结束本组数据的输出。

样例输入1 

5
1 2 -1 -1 1
5
1 -1 -1 2 2
0

样例输出1

2
1
1
POP ERROR

解答:建立顺序栈。入栈操作:先将数据存在栈顶所在位置,再将栈顶加1;出栈操作:先将栈顶减1,再取出栈顶元素。

#include<stdio.h>
#include<stdlib.h>
#define maxn 1000

typedef struct node
{
	int *top;
	int *base;
	int maxsize;
} Stack;

int main()
{
	int n;
	Stack st;
	st.base=(int *)malloc(maxn*sizeof(int));
	st.maxsize=maxn;
	while(1)
	{
		st.top=st.base;
		scanf("%d",&n);
		if(n==0)
			break;
		int *a=(int *)malloc((n+1)*sizeof(int));
		for(int i=0; i<n; i++)
		{
			scanf("%d",&a[i]);
		}
		for(int i=0; i<n; i++)
		{
			if(a[i] != -1)
			{
				*st.top=a[i];
				st.top++;
			}
			else
			{
				if(st.top!=st.base)
				{
					st.top--;
					printf("%d\n",*st.top);
				}
				else
				{
					printf("POP ERROR\n");
					break;
				}
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZLambert/article/details/81742229