大概80行代碼,如下,有需要自取。(數據結構教程 第五版 李春葆)
這次實驗是順序棧的操作,其中取棧頂元素的操作根據自己的情況取捨。
實驗四 棧基本操作的實現
【實驗目的】
1.掌握棧的順序存儲表示。
2.掌握順序棧的基本操作,包括創建、入棧、出棧等算法。
【實驗內容】
編寫程序sqstack.cpp,實現順序棧的各種基本運算(假設棧中的元素類型爲char),並在此基礎上設計主程序main.cpp,完成如下功能:
1.初始化棧;
2.判斷棧是否爲空;
3.依次入棧元素a,b,c,d,e;
4.判斷棧是否爲空;
5.輸出出棧序列;
6.判斷棧是否爲空;
7.釋放棧。
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
}SeqStack;
void InitStack(SeqStack *&s) //初始化棧
{
s = (SeqStack *)malloc(sizeof(SeqStack));
s->top = -1;
}
void DestroyStack(SeqStack *&s)//釋放棧
{
free(s);
}
bool StackEmpty(SeqStack *s)//判斷是否爲空
{
return (s->top == -1);
}
bool Push(SeqStack *&s, ElemType e)//進棧
{
if(s->top == (MaxSize - 1))
return false;
s->top++;
s->data[s->top] = e;
return true;
}
bool Pop(SeqStack *&s, ElemType &e) //出棧
{
if(s->top == -1)
return false;
e = s->data[s->top];
s->top--;
return true;
}
bool GetTop(SeqStack *s, ElemType &e)//取棧頂元素 ,實驗報告裏面沒有出現,可有可無,後面的主函數沒有引用該函數。
{
if(s->top == -1)
return false;
e = s->data[s->top];
return true;
}
int main(int x, char *y[])
{
ElemType e;
SeqStack *s;
printf("棧的基本運算如下:\n");
printf(" 1.初始化棧\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.出棧序列:");
while(!StackEmpty(s))
{
Pop(s, e);
printf("%c ", e);
}
printf("\n");
printf(" 6.棧爲%s\n",(StackEmpty(s) ? "空" : "非空"));
printf(" 7.釋放棧\n");
DestroyStack(s);
return 0;
}
運行結果:
編譯器最好用C-free或者DEV c++,工具下載鏈接見我的專欄裏面《數據結構與算法》(單鏈表的基本操作)。