Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <iostream>

using namespace std;

class Stack {
private:
struct Node {
int data;
Node* next;

Node(int data) : data(data), next(nullptr) {}


};

Node* top;

public:
Stack()
: top(nullptr) {
}

~Stack() {
while (!isEmpty()) {
pop();
}
}

void push(int data) {


Node* newNode = new Node(data);
newNode->next = top;
top = newNode;
}

void pop() {
if (isEmpty()) {
return;
}
Node* temp = top;
top = top->next;
delete temp;
}

int peek() {
if (isEmpty()) {
return -1;
}
return top->data;
}

bool isEmpty() { return top == nullptr; }


};

int main()
{
Stack stack;
int n;
cin >> n;
char sign;
int value;

Stack ans;
for (int i = 0; i < n; ++i){
cin >> sign;
if(sign == '+'){
cin >> value;
stack.push(value);
}
else{
ans.push(stack.peek());
stack.pop();
}
}

Stack tmp;

while (!ans.isEmpty()) {
tmp.push(ans.peek());
ans.pop();
}

while (!tmp.isEmpty()) {
cout << tmp.peek() << "\n";
tmp.pop();
}

return 0;
}

You might also like