顺序栈,这种是王道数据结构的实现方法,其实本质就是一个数组,已经静态分配好了空间,出栈的时候的操作其实也没有把栈顶元素从内存中删去,而是直接下标移动一位
#include <iostream>
#define MaxSize 20
using namespace std;
typedef struct{
int data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S){
S.top=-1;
}
bool Push(SqStack &S,int x){
if(S.top==MaxSize-1)
return false;
S.data[++S.top]=x;
return true;
}
bool Pop(SqStack &S){
if(S.top==-1)
return false;
S.top--;
}
bool GetTop(SqStack S,int &x){
if(S.top==-1)
return false;
x=S.data[S.top];
}
int main()
{
SqStack S;
cout << "Hello world!" << endl;
return 0;
}
顺序栈的第二种实现方式(指针)
#include <iostream>
using namespace std;
#define MaxSize 20
typedef struct{
int *base;
int *top;
int stacksize;
}SqStack;//顺序栈
bool InitStack(SqStack &S)
{
S.base=new int[MaxSize];
if(!S.base) return false;
S.top=S.base;
S.stacksize=MaxSize;
}
bool Push(SqStack &S,int e){
if(S.top-S.base==S.stacksize) return false;//满
*S.top++=e;//存入元素再栈顶指针+1
return true;
}
int Pop(SqStack &S){
int e;
if(S.top==S.base)return -1;//空
e=*--S.top;return e;//栈顶指针-1,并返还删去的栈顶元素
}
int GetTop(SqStack S){
if(S.top!=S.base){//非空
return *(S.top-1);
}return 9999;
}
int main()
{
SqStack S;
InitStack(S);
Push(S,1);Push(S,2);Push(S,3);
cout<<"栈顶元素:"<<GetTop(S)<<endl;
cout<<"出栈的元素为:"<<Pop(S)<<endl;
cout<<"栈顶元素:"<<GetTop(S)<<endl;
cout<<"出栈的元素为:"<<Pop(S)<<endl;
cout<<"栈顶元素:"<<GetTop(S)<<endl;
cout<<"出栈的元素为:"<<Pop(S)<<endl;
cout<<"栈顶元素:"<<GetTop(S)<<endl;
cout<< "Hello world!" << endl;
return 0;
}
链式存储,本质上就是头插法,然后依旧头删
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode,*LinkStack;
bool InitStack(LinkStack &S){
S=NULL;
return true;
}
bool Push(LinkStack &S,int e){
StackNode* p=(StackNode *)malloc(sizeof(StackNode));
p->data=e;
p->next=S;
S=p;
return true;
}
bool Pop(LinkStack &S){
if(S==NULL) return false;
StackNode* p=(StackNode *)malloc(sizeof(StackNode));
p=S;
S=S->next;
delete p;
return true;
}
int GetTop(LinkStack S){
if(S!=NULL)
return S->data;
}
int main()
{
LinkStack S;
cout << Push(S,1)<< endl;cout << Push(S,2)<< endl;cout << Push(S,3)<< endl;
cout << GetTop(S) << endl;
cout << "Hello world!" << endl;
return 0;
}