栈学习笔记(二)

今天开始用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--; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值