問題及代碼:
/*
Copyright (c)2015,煙臺大學計算機與控制工程學院
All rights reserved.
文件名稱:第6周項目1 - 建立順序棧算法庫.cpp
作 者:朱振華
完成日期:2015年10月9日
版 本 號:v1.0
問題描述:定義順序棧存儲結構,實現其基本運算,並完成測試。
輸入描述:若干數據。
程序輸出:各個步驟的文字敘述及其數據的輸出。
*/
1.頭文件:
#include<stdio.h>
#include<malloc.h>
#define maxsize 100
typedef char ElemType ;
typedef struct
{
char date[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); //輸出棧
2.源文件:
#include"sqstack.h"
void InitStack(SqStack *&s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
void DestroyStack(SqStack *&s)
{
free(s);
}
bool StackEmpty(SqStack *s)
{
if(s->top==-1)
{
return true;
}
else return false;
}
int StackLength(SqStack *s)
{
return s->top+1;
}
bool Push(SqStack *&s,ElemType e)
{
if(s->top==maxsize-1)
{
return false;
}
s->top++;
s->date[s->top]=e;
return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
if(s->top==-1)
{
return false;
}
e=s->date[s->top];
s->top--;
return true;
}
bool GetTop(SqStack *s,ElemType &e)
{
if(s->top==-1)
{
return false;
}
e=s->date[s->top];
s->top--;
return true;
}
void DispStack(SqStack *l)
{
int i=0;
while(i<=l->top)
{
printf("%c ",l->date[i]);
i++;
}
printf("\n");
}
3.main函數:
#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;
}
運行結果:
總結:
這個項目主要是棧的建立,釋放,進棧出棧和棧的最終輸出,這是最基本的棧的知識,建立此算法庫方便日後對棧的應用。