栈的C语言模拟(先进后出)
#include<stdio.h>
int stack[10];
int top=0; // 栈的顶
void push(int x) // 入栈函数
{
top++;
stack[top]=x; // x进入栈的顶部
}
void pop() // 删去顶端的函数
{
stack[top]=-1; // 用 -1 标记该位置为空
top--;
}
/* 判断栈是不是空的
top==0 空
否则 非空
也可以用下面的函数
bool empty()
{
if(top) return true;
return false;
}
接下来看一道经典的栈的题目
题目传送门:https://vjudge.net/problem/HDU-1022;
代码如下
#include<stdio.h>
int top=0;
char stack[10];
void push(char n)
{
top++;
stack[top]=n;
}
void pop()
{
stack[top]=0;
top--;
}
int main()
{
int i,c[30]={0},n,k,step;
char a[10],b[10],ch;
while(scanf("%d",&n)!=EOF)
{
top=0;
for(i=1;;)
{
scanf("%c",&ch);
if(ch>='1' && ch<='9')
{
a[i]=ch;
if(i==n) break;
i++;
}
}
for(i=1;;)
{
scanf("%c",&ch);
if(ch>='1' && ch<='9')
{
b[i]=ch;
if(i==n) break;
i++;
}
}
push(a[1]);
i=1;
k=1;
step=1;
c[1]=1;
while(i<=n)
{
if(stack[top]==b[k])
{
pop();
k++;
step++;
c[step]=2;
}
else
{
i++;
push(a[i]);
step++;
c[step]=1;
}
if(i==n && stack[top]!=b[k])
break;
if(k>n) break;
if(stack[top]==b[k])
{
pop();
k++;
step++;
c[step]=2;
}
else
{
i++;
add(a[i]);
step++;
c[step]=1;
}
}
if(top) printf("No.\n");
else
{
printf("Yes.\n");
for(i=1;i<=step;i++)
{
if(c[i]==1)
printf("in\n");
if(c[i]==2)
printf("out\n");
}
}
printf("FINISH\n");
}
return 0;
}
栈的 C++函数调用
#include<stack> // 栈的头文件
using namespace std;
stack<类型>变量名; // 定义一个名为xxx的 xx类型的栈
// 例如 stack<int>a;
// 函数调用
a.pop(); //从顶端删除一个元素
a.push(x) // 将 x 添加在栈的顶端
a.empty() // 判断栈中有无元素
//清空栈的方法
while(!a.empty()) a.pop();