实现顺序栈和链栈的、栈的初始化、入栈、出栈、获取栈顶元素功等功能。
顺序栈
代码如下:
#include "pch.h" #include <iostream> #include<Windows.h> #include<string> using namespace std; #define OK 1 #define ERROR 0 #define OVER -2 #define MAXSIZE 100 typedef int Status; //返回状态 //顺序表结构体 struct SqStack { char *base; char *top; int StackSize; }; //初始化顺序栈 Status InitStack(SqStack &S) { S.base = new char[MAXSIZE]; if (!S.base) { Sleep(3000); exit(OVER); } S.top = S.base; S.StackSize = MAXSIZE; return OK; } //入栈 Status Push(SqStack &s, char &e) { if (s.top - s.base == s.StackSize) { return ERROR; } *(s.top) = e; //元素入栈,栈顶指针+1 s.top++; return OK; } //出栈 Status Pop(SqStack &s, char &e) { if (s.base == s.top) { return ERROR; } e = *(s.top - 1); //这是出栈元素 s.top--; return OK; } //得到栈顶元素 char GetTop(SqStack &s) { if (s.top != s.base) { return *(s.top - 1); } } //打印栈元素 void PrintStack(SqStack &s) { if (s.top != s.base) { cout << "栈的元素为:"; int k = 0; for (int i = (s.top - s.base); i > 0; i--) { cout << *(s.top - 1) << " "; --s.top; k++; } for (int j = 0; j <k; j++) { ++s.top; } } } int main() { SqStack s; InitStack(s); int n; cout << "请输入初始个数:"; cin >> n; cout << "请输入元素:" << endl; for (int i = 0; i < n; i++) { char p; cin >> p; Push(s, p); } PrintStack(s); cout << "栈顶为:" << GetTop(s) << endl; char p1; Pop(s, p1); cout << "出栈后"; PrintStack(s); return 0; }
结果如下:
链栈
代码如下:
#include "pch.h" #include <iostream> #include<string> #include<Windows.h> using namespace std; #define OK 1 #define ERROR 0 #define OVER -2 #define MAXSIZE 100 typedef int Status; //返回状态 typedef struct StackNode { char date; StackNode *next; }*LinkStack; //初始化链栈 Status InitStack(LinkStack s) { s = NULL; return OK; } //入栈 Status Push(LinkStack s, char e) { LinkStack p; p = new StackNode; p->date = e; p->next = s; s = p; return OK; } //出栈 Status Pop(LinkStack s, char &e) { LinkStack p; if (s == NULL) { return ERROR; } e = s->date; p = s; //用p临时保存栈顶元素的值 s = s->next; //修改栈顶指针 delete p; return OK; } //取栈顶元素的值 char Getchar(LinkStack s) { if (s!=NULL) { return s->date; } cout << "栈为空,无法取栈顶元素!" << endl; return ERROR; } int main() { StackNode s; InitStack(&s); char a, b, c; a = 'c', b = 'b', c = 'a'; Push(&s, a); Push(&s, b); Push(&s, c); cout << "出栈前栈顶为:"; Getchar(&s); char e; Pop(&s,e); cout << "出栈后栈顶为:"; return 0; }
结果如下: