今天开始用c语言实现栈的基本操作。因为没有什么模版可言,所以让队长给写了一个代码。把代码贴出来,也算是自己的资料了。现在要做的就是研究一下代码,然后自己写出一个简单的栈的代码。
这是用c写成的。
#include<iostream> using namespace std; struct mystack{ int a[6]; int pos; }s; void push(int elem) { s.pos++; s.a[s.pos]=elem; } int top() { return s.a[s.pos]; } void pop() { s.pos--; } int main() { s.pos=-1; push(1); push(2); cout<<top()<<endl; pop(); cout<<top()<<endl; } 另外下面是另外一个同学写的
#include<stdio.h> struct Stack { char stack[10005]; int top; }; void InitStack(Stack& a) { a.top=-1; } void push(Stack& a,char item) { a.top++; a.stack[a.top]=item; } void pop(Stack& a) { a.top--; } int main() { int a,b,c,n; char ch; scanf("%d",&n); getchar(); while(n--) { Stack a; InitStack(a); while(scanf("%c",&ch)&&ch!='\n') { if(ch=='['||ch=='(') push(a,ch); else { if(a.stack[a.top]=='['&&ch==']') { pop(a);} else if(a.stack[a.top]=='('&&ch==')') pop(a); else push(a,ch); } } if(a.top==-1) printf("Yes\n"); else printf("No\n"); } }
这两段代码很多地方都有相同之处。队长写的是int型的,下面的是char型的。
另外积累一个char型栈的模版。
#include<stdio.h>
struct Stack
{
char str[10005];
int top;
};
void InitStack(Stack& a)
{
a.top=-1;
}
void push(Stack& a,char item)
{
a.top++;
a.str[a.top]=item;
}
void pop(Stack& a)
{
a.top--;
}