C++ 数据结构-栈

来源:互联网 发布:人类学 知乎 编辑:程序博客网 时间:2024/06/03 14:09

(stack)是一种先进后出的基本数据结构


一、实现



(一)手写

需要一个栈顶指针(指向空位置),数组作栈

(在结构体内写更好)

#include <iostream>using namespace std;#define EMPTY -9999999int stack[1001];int top = 1;int n, tmp;void push(const int x) { stack[top ++] = x;}bool empty() {if(top == 1) return true;return false;}int pop() {                      if(empty()) return EMPTY;return stack[-- top];}int Func_top() {                    return stack[top-1];         }int main() {cin >> n;for(int i=0; i<n; i++) {cin >> tmp;push(tmp);}while(!empty()) {cout << Func_top() << " ";pop();}return 0;}



(二)C++ STL


stack<int> a;

常用操作:

a. push(x) 将x入栈

a. top() 访问栈顶元素

a. pop() 弹出(不返回)栈顶元素

a. empty() 判断栈是否为空

a.size() 返回栈中元素个数


#include <iostream>#include <stack>using namespace std;stack<int> a;int n, tmp;int main() {cin >> n;for(int i=0; i<n; i++) {cin >> tmp;a.push(tmp);}while(!a.empty()) {cout << a.top() << " ";a.pop();}return 0;}


二、应用