第五週 項目 1 - 建立順序棧算法庫

sqstack.h代碼

/* 
*Copyright (c) 2017,煙臺大學計算機與控制工程學院 
*All rights reserved. 
*文件名稱: 
*作    者:陳軍正 
*完成日期:2017年10月10日 
*版 本 號:v1.0 
* 
* 定義順序棧存儲結構,實現其基本運算,並完成測試。
*/ 
#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);  //輸出棧
main.cpp代碼
#include <stdio.h>
#include "sqstack.h"
#include <iostream>
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);
	system("pause");
	return 0;
}


sqstack.cpp 代碼

#include <iostream>
#include "sqstack.h"
#include <malloc.h>
using namespace std;
void InitStack(SqStack *&s)    //初始化棧
{
	s = (SqStack *)malloc(sizeof(SqStack));
	s->top = -1;
}
void DestroyStack(SqStack *&s)  //銷燬棧
{
	free(s);
}
bool StackEmpty(SqStack *s)     //棧是否爲空
{
	return (s->top == -1);	
}
int StackLength(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 false;
}
void DispStack(SqStack *s)  //輸出棧
{
	int i;
	for ( i = s->top; i >=0; i--)
	{
		cout << s->data[i] << " ";
	}
}


運行結果

總結:學習棧的基本使用


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章