数据结构——栈
一、用数组实现栈的功能
#include<iostream>//用数组实现栈的功能 using namespace std; #define MAX_SIZE 101//定义此栈最大空间为101 int A[MAX_SIZE]; int top = -1;//定义全局变量top表示栈顶,当栈为空时,top=-1 void Push(int x) {//压栈操作 if (top == MAX_SIZE - 1) { cout << "Error:Stack overflow"; return; } else { A[++top] = x;//等价于top++ A[top]=x; } } void Pop() {//弹栈操作 if (top == -1) { cout << "Error:No element to pop"; return; } else { top--; } } int Top() {//输出栈顶的值 return A[top]; } void Print() {//打印整个栈 for (int i = 0; i <= top; i++) { cout << A[i] << " "; } cout << endl; } int main() { Push(1); Push(3); Print(); Push(10); Pop(); Print(); Push(9); Print(); cout << Top(); return 0; }
二、用链表实现栈的功能
#include<iostream> using namespace std; struct Node { int data; Node* link; }; Node* top = NULL;//定义栈顶为全局变量 int num = -1; void Push(int x) { Node* temp = new Node;//开辟一个新的节点 temp->data = x;//将新的节点的数据端改成x temp->link = top;//将新的节点的地址端改成top top = temp;//更新top num++; } void Pop() { Node* temp = new Node; if (top == NULL)return; else { temp = top; top = top->link; delete temp; num--; } } int Top() { return top->data; } void Print() { int a[10]; int i = 0; Node* temp = top; while (temp != NULL) {//用数组存放链表data,然后将数组逆序输出 a[i]=temp->data; temp = temp->link; i++; } for (int j = num; j >= 0; j--) { cout << a[j] << " "; } cout << endl; } int main() { Push(1); Push(3); Print(); Push(10); Pop(); Print(); Push(9); Print(); cout << Top(); }
三、用栈反转一个字符串
#include<iostream> #include<stack> using namespace std; void Reverse(char a[], int n) { stack<int> S;//建立一个名为S的栈 for (int i = 0; i < n; i++) { S.push(a[i]); } for (int i = 0; i < n; i++) { a[i] = S.top(); S.pop(); } } int main() { char a[20]; int n; cout << "请输入字符串:"; cin >> a; n = strlen(a); Reverse(a,n); cout << "反转后的字符串:"<<a; }
本文作者:Smera1d0
本文链接:https://www.cnblogs.com/Smera1d0/p/17697984.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步