棧的基本操作及實現(順序棧)

順序存儲結構來實現的棧稱爲順序棧,它利用一組地址連續的存儲單元存放自棧底到棧頂的數據元素,同時附設一個指針top來指示當前棧頂的位置。
(注意,“&”是c++特有的用來表示引用調用,所以此文件應以.cpp後綴保存)
結構體爲:

#define MaxSize 50
typedef int ElemType;

typedef struct{
    ElemType data[MaxSize];
    int top;
}SqStack;

基本方法爲:

void InitStack(SqStack &s); //初始化
bool StackEmpty(SqStack &s);  //判空
bool Push(SqStack &s, ElemType e); //入棧
bool Pop(SqStack &s, ElemType &e); //出棧
bool GetTop(SqStack s, ElemType &e); //獲取棧頂元素

一個測試函數main()如下所示:

int main()
{
    int s, i = 0;
    SqStack sqStack;
    InitStack(sqStack);
    
    scanf("%d", &s);
    while(s != 9999)
    {
        Push(sqStack, s);
        scanf("%d", &s);
    }
    Pop(sqStack, i);
    GetTop(sqStack, s);
    printf("%d", s);
    
    return 0;
}

運行結果爲:
順序棧的運行結果
完整的源程序爲:

#include "stdio.h"
#include "stdlib.h"

#define MaxSize 50
typedef int ElemType;

typedef struct{
    ElemType data[MaxSize];
    int top;
}SqStack;

void InitStack(SqStack &s);
bool StackEmpty(SqStack &s);
bool Push(SqStack &s, ElemType e);
bool Pop(SqStack &s, ElemType &e);
bool GetTop(SqStack s, ElemType &e);
bool ClearStack(SqStack &s);

int main()
{
    int s, i = 0;
    SqStack sqStack;
    InitStack(sqStack);
    
    scanf("%d", &s);
    while(s != 9999)
    {
        Push(sqStack, s);
        scanf("%d", &s);
    }
    Pop(sqStack, i);
    GetTop(sqStack, s);
    printf("%d", s);
    
    return 0;
}

void InitStack(SqStack &s)
{
    s.top = -1;
}

bool StackEmpty(SqStack &s)
{
    if(s.top == -1)
        return true;
    else
        return false;
}

bool Push(SqStack &s, ElemType e)
{
    if(s.top == MaxSize - 1)
        return false;
    s.data[++s.top] = e;
    return true;
}

bool Pop(SqStack &s, ElemType &e)
{
    if(s.top == -1)
        return false;
    e = s.data[s.top--];
    return true;
}

bool GetTop(SqStack s, ElemType &e)
{
    if(s.top == -1)
        return false;
    e = s.data[s.top];
    return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章