【数据结构学习笔记】栈的顺序实现和链式实现 C/C++

顺序栈,这种是王道数据结构的实现方法,其实本质就是一个数组,已经静态分配好了空间,出栈的时候的操作其实也没有把栈顶元素从内存中删去,而是直接下标移动一位

#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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值