棧的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;
## 代碼如下
```c
#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++函數調用
```cpp
#include<stack> // 棧的頭文件/<stack>
using namespace std;
stack變量名; // 定義一個名為xxx的 xx類型的棧
// 例如 stack
// 函數調用
a.pop(); //從頂端刪除一個元素
a.push(x) // 將 x 添加在棧的頂端
a.empty() // 判斷棧中有無元素
//清空棧的方法
while(!a.empty()) a.pop();
```
閱讀更多 profat 的文章