C++数据结构顺序栈的初始化、元素进栈、出栈、判断是否为空

mac2024-12-05  25

记录一下今天学的代码 , 关于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; }

 

最新回复(0)