我們學(xué)數(shù)據(jù)結(jié)構(gòu)老師用的是C但是我本身語言學(xué)的是C++
會有些許差別下面會針對某些點(diǎn)做備注
是根據(jù)嚴(yán)巍敏老師的數(shù)據(jù)結(jié)構(gòu)書所寫 其中
而王道天勤中用S.top=-1為??諚l件并且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
我自己總結(jié)一下下文,要是將來看不懂可以往下翻
他們的區(qū)別就是C中用typedef struct,}后面的是和struct Stu一樣的別名,struct后面可以省略
C++中用struct的話 }后面是直接定義了變量,如果使用了typedef就和C一個用法
記一下寫的過程中出現(xiàn)的問題
因?yàn)闀嫌玫氖莔alloc動態(tài)分配的空間,我一直對比怎么變成new
其實(shí)不用,就直接用new的使用方法就可以(S.base因?yàn)橐呀?jīng)定義所以前面根本不用加聲明啊,不要被malloc干擾 會哪個用哪個就好不需要一直對比差別)
所以我一直沒有計算出來?xiàng)iL度的原因是因?yàn)楦緵]理解,這個結(jié)構(gòu)體的意思是*base是一個數(shù)組(也就是這個棧)的頭指針,他需要帶著一個動態(tài)數(shù)組(增加數(shù)組長度的push函數(shù)我沒寫……王道上是直接在這個結(jié)構(gòu)體中定義一個靜態(tài)數(shù)組),我一直以為一個指頭一個指尾完全沒考慮中間有東西……
下文摘抄自百度
1 首先:
在C中定義一個結(jié)構(gòu)體類型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在聲明變量的時候就可:Stu stu1;
(如果沒有typedef就必須用struct Student stu1;來聲明)
這里的Stu實(shí)際上就是struct Student的別名。Stu==struct Student
另外這里也可以不寫Student ↓
typedef struct
{
int a;
}Stu;
(于是也不能struct Student stu1;了,必須是Stu stu1;)
但在c++里很簡單,直接
struct Student
{
int a;
};
于是就定義了結(jié)構(gòu)體類型Student,聲明變量時直接Student stu2;
2.其次:
在c++中如果用typedef的話,相當(dāng)于C的用法:
struct Student
{
int a;
}stu1; //stu1是一個變量
typedef struct Student2
{
int a;
}stu2; //stu2是一個結(jié)構(gòu)體類型=struct Student
使用時可以直接訪問stu1.a
但是stu2使用則 stu2 s2;