연결리스트로 구현한 스택
#include <bits/stdc++.h>
#define ll long long
using namespace std;
class Node {
public:
Node* link;
int data;
Node(int data = 0) : link(nullptr), data(data) {}
};
class Lstack
{
public:
Node* top;
Node* cur;
Lstack()
{
top = new Node();
}
void push(int data)
{
Node* newNode = new Node(data);
newNode->link = top;
top = newNode;
}
void pop()
{
if (top->link != NULL)
{
cout << top->data << "\n";
Node* temp = top;
top = top->link;
delete temp;
return;
}
cout << "-1\n";
}
void empty()
{
if (top->link == NULL)
{
cout << "1\n";
}
else
cout << "0\n";
}
void tap()
{
if (top->link == NULL)
cout << "-1\n";
else
cout << top->data << "\n";
}
void size()
{
int sizeN = 0;
Node* temp = top;
while (temp->link != NULL)
{
temp = temp->link;
sizeN++;
}
cout << sizeN << "\n";
}
};
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n; cin >> n;
Lstack st;
for (int i = 0; i < n; i++)
{
string s; cin >> s;
if (s == "push")
{
int tmp; cin >> tmp;
st.push(tmp);
}
if (s == "top")
{
st.tap();
}
if (s == "size")
{
st.size();
}
if (s == "pop")
{
st.pop();
}
if (s == "empty")
st.empty();
}
return 0;
}
Leave a comment