我们学数据结构老师用的是C但是我本身语言学的是C++
会有些许差别下面会针对某些点做备注
是根据严巍敏老师的数据结构书所写 其中
而王道天勤中用S.top=-1为栈空条件并且top总指向栈顶元素
#include<iostream>
#define STACK_INIT_SIZE 100
using namespace std;
typedef struct {
int *base;
int *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S){
S.base=new int[STACK_INIT_SIZE];
S.top=S.base;
}
void DestroyStack(SqStack &S){
delete(S.base);
S.base=S.top=NULL;
}
void ClearStack(SqStack &S){
S.top=S.base;
}
bool StackEmpty(SqStack S){
if(S.top==S.base)
return true;
else
return false;
}
int StackLength(SqStack S){
return (S.top-S.base);
}
bool GetTop(SqStack S,int &e){
if(S.top==S.base)return false;
e=*(S.top-1);
return true;
}
bool Push(SqStack &S,int e){
if(S.top-S.base==S.stacksize)
return false;
*(S.top++)=e;
return true;
}
bool Pop(SqStack &S,int &e){
if(S.top==S.base)return false;
e=*(--S.top);
return true;
}
int main(){
SqStack S;
InitStack(S);
int a,k;
while(cin>>a){
Push(S,a);
}
int length=StackLength(S);
cout<<length<<endl;
while(S.top!=S.base){
GetTop(S,k);
cout<<k;
Pop(S,k);
}
return 0;
}
typedef struct和struct
我自己总结一下下文,要是将来看不懂可以往下翻
他们的区别就是C中用typedef struct,}后面的是和struct Stu一样的别名,struct后面可以省略
C++中用struct的话 }后面是直接定义了变量,如果使用了typedef就和C一个用法
记一下写的过程中出现的问题
因为书上用的是malloc动态分配的空间,我一直对比怎么变成new
其实不用,就直接用new的使用方法就可以(S.base因为已经定义所以前面根本不用加声明啊,不要被malloc干扰 会哪个用哪个就好不需要一直对比差别)
所以我一直没有计算出来栈长度的原因是因为根本没理解,这个结构体的意思是*base是一个数组(也就是这个栈)的头指针,他需要带着一个动态数组(增加数组长度的push函数我没写……王道上是直接在这个结构体中定义一个静态数组),我一直以为一个指头一个指尾完全没考虑中间有东西……
下文摘抄自百度
1 首先:
在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在声明变量的时候就可:Stu stu1;
(如果没有typedef就必须用struct Student stu1;来声明)
这里的Stu实际上就是struct Student的别名。Stu==struct Student
另外这里也可以不写Student ↓
typedef struct
{
int a;
}Stu;
(于是也不能struct Student stu1;了,必须是Stu stu1;)
但在c++里很简单,直接
struct Student
{
int a;
};
于是就定义了结构体类型Student,声明变量时直接Student stu2;
2.其次:
在c++中如果用typedef的话,相当于C的用法:
struct Student
{
int a;
}stu1; //stu1是一个变量
typedef struct Student2
{
int a;
}stu2; //stu2是一个结构体类型=struct Student
使用时可以直接访问stu1.a
但是stu2使用则 stu2 s2;