數據結構之自建算法庫——順序棧

順序棧算法庫採用程序的多文件組織形式,包括兩個文件:
  
  1.頭文件:sqstack.h,包含定義順序棧數據結構的代碼、宏定義、要實現算法的函數的聲明;

#ifndef SQSTACK_H_INCLUDED
#define SQSTACK_H_INCLUDED

#define MaxSize 100
typedef char ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int top;                //棧指針
} SqStack;                  //順序棧類型定義

void InitStack(SqStack *&s);    //初始化棧
void DestroyStack(SqStack *&s);  //銷燬棧
bool StackEmpty(SqStack *s);     //棧是否爲空
int StackLength(SqStack *s);  //返回棧中元素個數——棧長度
bool Push(SqStack *&s,ElemType e); //入棧
bool Pop(SqStack *&s,ElemType &e); //出棧
bool GetTop(SqStack *s,ElemType &e); //取棧頂數據元素
void DispStack(SqStack *s);  //輸出棧

#endif // SQSTACK_H_INCLUDED

  2.源文件:sqstack.cpp,包含實現各種算法的函數的定義

#include <stdio.h>
#include <malloc.h>
#include "sqstack.h"

void InitStack(SqStack *&s)
{
    s=(SqStack *)malloc(sizeof(SqStack));
    s->top=-1;
}
void DestroyStack(SqStack *&s)
{
    free(s);
}
int StackLength(SqStack *s)  //返回棧中元素個數——棧長度
{
    return(s->top+1);
}
bool StackEmpty(SqStack *s)
{
    return(s->top==-1);
}
bool Push(SqStack *&s,ElemType e)
{
    if (s->top==MaxSize-1)    //棧滿的情況,即棧上溢出
        return false;
    s->top++;
    s->data[s->top]=e;
    return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
    if (s->top==-1)     //棧爲空的情況,即棧下溢出
        return false;
    e=s->data[s->top];
    s->top--;
    return true;
}
bool GetTop(SqStack *s,ElemType &e)
{
    if (s->top==-1)         //棧爲空的情況,即棧下溢出
        return false;
    e=s->data[s->top];
    return true;
}

void DispStack(SqStack *s)  //輸出棧
{
    int i;
    for (i=s->top;i>=0;i--)
        printf("%c ",s->data[i]);
    printf("\n");
}

  3.在同一項目(project)中建立一個源文件(如main.cpp),編制main函數,完成相關的測試工作。 例:

#include <stdio.h>
#include "sqstack.h"

int main()
{
    ElemType e;
    SqStack *s;
    printf("(1)初始化棧s\n");
    InitStack(s);
    printf("(2)棧爲%s\n",(StackEmpty(s)?"空":"非空"));
    printf("(3)依次進棧元素a,b,c,d,e\n");
    Push(s,'a');
    Push(s,'b');
    Push(s,'c');
    Push(s,'d');
    Push(s,'e');
    printf("(4)棧爲%s\n",(StackEmpty(s)?"空":"非空"));
    printf("(5)棧長度:%d\n",StackLength(s));
    printf("(6)從棧頂到棧底元素:");DispStack(s);
    printf("(7)出棧序列:");
    while (!StackEmpty(s))
    {
        Pop(s,e);
        printf("%c ",e);
    }
    printf("\n");
    printf("(8)棧爲%s\n",(StackEmpty(s)?"空":"非空"));
    printf("(9)釋放棧\n");
    DestroyStack(s);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章