问题描述:
定义一个单调栈:每次整数n入栈时,如果栈顶元素大于n,则栈顶元素出 栈,并且继续判断栈顶元素是否大于n,大于则出栈,重复操作,直到栈顶 元素不大于n,n入栈。入栈完毕。例如:栈中元素为2 3 7,如栈元素为6, 则7出栈,6入栈,最后结果为2 3 6;
解题思路:
没什么讲的,就是按照题目的逻辑就行。栈用数组就好。
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
long temp;
long *s;
int top = -1;
scanf("%d",&n);
s = (long *)malloc(sizeof(long) * n);
while(n--)
{
scanf("%d",&temp);
if(top == -1)
{
top++;
s[top] = temp;
}
else
{
while(top != -1 && s[top] > temp)
{
top--;
}
top++;
s[top] = temp;
}
}
for(n = 0; n < top; n++)
{
printf("%d ",s[n]);
}
printf("%d",s[top]);
free(s);
return 0;
}