栈的顺序存储与链式存储

栈的顺序存储

#include<iostream>
#include<cstdlib>
using namespace std;
#define MaxSize 100
#define ElementType int
typedef struct SNode *Stack;
struct SNode{
    ElementType data[MaxSize];
    int top;
};
//建立空栈 
Stack CreateStack()
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->top = -1;
    return S;
}
//入栈
void Push(Stack PtrS,ElementType X)
{
    if(PtrS->top==MaxSize-1)
        cout<<"堆栈满"<<endl;  
    else
        PtrS->data[++(PtrS->top)]=X;
 } 
//出栈
#define Error -1
ElementType Pop(Stack PtrS)
{
    if(PtrS->top==-1){
        cout<<"空栈"<<endl;
        return Error; 
    }else{
        return (PtrS->data[(PtrS->top)--]);
    }
}
//例子 
int main()
{
    int i;
    Stack s = CreateStack();
    for(i=0;i<10;i++)
        Push(s,i);
    for(i=0;i<10;i++)
        cout<<Pop(s)<<" ";
    return 0;
}

这里写图片描述

栈的链式存储

#include<iostream>
#include<cstdlib>
using namespace std;
#define ElementType int
typedef struct SNode *Stack;
struct SNode{
    ElementType data;
    struct SNode *next; 
};
//建立带头结点的空链栈
Stack CreateStack()
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->next = NULL;
    return S;
 } 
 //判栈空 
 bool IsEmpty ( Stack S )
{ /* 判断堆栈S是否为空,若是返回true;否则返回false */
    return ( S->next == NULL );
}
//入栈
void Push(Stack S,ElementType X)
{
    struct SNode *tmp = (struct SNode *)malloc(sizeof(struct SNode));  //申请新结点空间 
    tmp->data = X;
    tmp->next = S->next;            //在栈的顶部进行插入 
    S->next = tmp;
}
//出栈
#define Error -1
ElementType Pop(Stack S)
{
    struct SNode *tmp;
    ElementType TopElem;
    if(IsEmpty (S)){
        cout<<"链栈为空"<<endl;
        return Error; 
    }else{
        tmp = S->next;               //记录被删结点 
        S->next = tmp->next;         //删除结点 
        TopElem = tmp->data;         
        free(tmp);                   //释放结点空间 
        return TopElem;
    }
 } 
int main()
{
    int i;
    Stack s = CreateStack();
    for(i=0;i<10;i++)
        Push(s,i);
    for(i=0;i<10;i++)
        cout<<Pop(s)<<" ";
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值