欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈的顺序存储与链式存储

程序员文章站 2022-03-12 17:15:28
...

栈的顺序存储

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

栈的顺序存储与链式存储

相关标签: 堆栈