#ifndef STACK_H
#define STACK_H
#include
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int data[MAX_SIZE];
int top; // 棧頂索引,0 表示空
public:
Stack(); // 構造函數
void push(int x); // 入棧
int pop(); // 出棧
int peek() const; // 取頂
bool empty() const;
int size() const;
void display() const;
};
#endif
#include "stack.h"
Stack::Stack() : top(0) {}
void Stack::push(int x) {
if (top == MAX_SIZE) {
cout << "Stack overflow!\n";
return;
}
data[top++] = x;
cout << "Pushed " << x << endl;
}
int Stack::pop() {
if (top == 0) {
cout << "Stack underflow!\n";
return 0;
}
return data[--top];
}
int Stack::peek() const {
if (top == 0) return 0;
return data[top-1];
}
bool Stack::empty() const { return top == 0; }
int Stack::size() const { return top; }
void Stack::display() const {
cout << "Stack (top to bottom): ";
for (int i = top-1; i >= 0; --i) cout << data[i] << ' ';
cout << endl;
}
#include "stack.h"
int main() {
Stack s;
char op;
int val;
cout << "Commands: p=push, o=pop, t=top, s=size, d=display, q=quit\n";
while (cin >> op) {
switch (op) {
case 'p': cin >> val; s.push(val); break;
case 'o': cout << "Popped: " << s.pop() << endl; break;
case 't': cout << "Top: " << s.peek() << endl; break;
case 's': cout << "Size: " << s.size() << endl; break;
case 'd': s.display(); break;
case 'q': return 0;
default: cout << "Unknown command\n";
}
}
return 0;
}
#include
stack s;
s.push(1); s.push(2);
cout << s.top(); // 2
s.pop();
cout << s.top(); // 1
cout << s.size(); // 1
底層默認 `deque`,也可指定 `vector`/`list`。生產代碼優先用 STL。