記錄一下今天學的代碼 , 關於c++順序棧
// sqstack.cpp : 順序棧初始化和輸出打印
//
#include "stdafx.h"
#include "iostream"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
typedef int Status;
using namespace std;
typedef struct Stack
{
char *base;
char *top;
int stacksize;
}SqStack;
//判斷棧是否爲空
bool isStackEmpty(SqStack &s){
if (s.top == s.base){
return true;
}
else{
return false;
}
}
//刪除棧頂元素,並返回
Status pop(SqStack &s){
ElemType e;
if (isStackEmpty(s)){
cout << "棧爲空!" << endl;
return false;
}
return *(--s.top);
}
//刪除棧頂元素,並返回
bool clearStack(SqStack &s){
while (!isStackEmpty(s)){
pop(s);
}
return true;
}
bool visit(ElemType e){
cout << e << "";
return true;
}
//輸出順序爲出棧的順序
void stackTraverse(SqStack &s){
if (isStackEmpty(s)){
cout << "棧爲空" << endl;
exit(0);
}
while (!isStackEmpty(s)){
visit(*(--s.top));
}
cout << endl;
}
//插入元素e爲棧頂元素
Status push(SqStack &s, ElemType e){
if (s.top - s.base >= s.stacksize){
s.base = (ElemType *)realloc(s.base, (s.stacksize + STACKINCREMENT)* sizeof(ElemType));
if (!s.base){
exit(-1);
}
s.top = s.base + s.stacksize;
s.stacksize += STACKINCREMENT;
}
*s.top = e;
s.top++;
}
//初始化棧
bool initStack(SqStack &s){
s.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s.base){
cout << "內存分配失敗" << endl;
exit(-1);
}
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
cout << "初始化順序棧成功" << endl;
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
bool tagbool;
SqStack s;
//(1)初始化棧
initStack(s);
//(2)判斷棧s是否爲空
tagbool = isStackEmpty(s);
cout << "判斷棧是否爲空" << tagbool << endl;
//(3)以此進棧元素
cout << "插入元素abcde" << endl;
push(s, 'a');
push(s, 'b');
push(s, 'c');
push(s, 'd');
push(s, 'e');
//(4)判斷棧s是否爲空
tagbool = isStackEmpty(s);
cout << "判斷棧是否爲空" << tagbool <<endl;
//(5)輸出出棧序列
cout << "輸出出棧序列" << endl;
stackTraverse(s);
//(6)判斷棧s是否爲空
tagbool = isStackEmpty(s);
cout << "判斷棧是否爲空" << tagbool << endl;
//(7)釋放棧
cout << "釋放棧" << endl;
clearStack(s);
getchar();
return 0;
}