牛客:AB1 【模板】栈
链接:【模板】栈_牛客题霸_牛客网
题解:
模拟实现一个栈,要有动态扩容机制
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;class Stack
{
private:int* _nums;int _capacity;//栈容量int _top;//栈顶指针
public://构造函数Stack():_nums(new int[10]),_capacity(10),_top(0){}//析构函数~Stack(){delete[] _nums;}//入栈void push(int x){//扩容if (_top == _capacity){_capacity *= 2;_nums = (int*)realloc(_nums, sizeof(int) * _capacity);}_nums[_top] = x;_top++;}//出栈(并输出栈顶)void pop(){if (_top > 0){int x = _nums[_top - 1];_top--;cout << x << endl;}else {cout << "error" << endl;}}//输出栈顶void top(){if (_top > 0) cout << _nums[_top - 1] << endl;else cout << "error" << endl;}
};void test()
{Stack s;int n = 0;cin >> n;cin.ignore(numeric_limits<streamsize>::max(), '\n');for (int i = 0; i < n; i++){string op;string str;getline(cin, str);stringstream ss(str);getline(ss, op, ' ');if (op == "push"){string x;getline(ss, x, ' ');s.push(stoi(x));}else if (op == "pop"){s.pop();}else if (op == "top"){s.top();}}
}
int main()
{test();return 0;
}