전공/자료구조
[자료 구조] C++ Singly Linked List로 Stack 구현
kar7mp5
2024. 3. 21. 23:56
728x90
#include <iostream>
using namespace std;
#define endl '\n'
struct Node {
int val;
Node* next;
};
class LinkedList {
public:
LinkedList();
int getSize() const;
bool isEmpty() const;
int getTop() const;
void push(const int& _val);
int pop();
private:
Node* head;
Node* tail;
int size;
};
LinkedList::LinkedList() {
head = nullptr;
tail = nullptr;
size = 0;
}
int LinkedList::getSize() const {
return size;
}
bool LinkedList::isEmpty() const {
if (size == 0)
return 1;
else
return 0;
}
int LinkedList::getTop() const {
if (isEmpty()) {
return -1;
}
return head->val;
}
void LinkedList::push(const int& _val) {
Node* newNode = new Node;
newNode->val = _val;
++size;
if (isEmpty()) {
head = newNode;
tail = newNode;
}
else {
Node* tmp = head;
head = newNode;
head->next = tmp;
}
}
int LinkedList::pop() {
if (isEmpty()) {
return -1;
}
Node* tmp = head->next;
int result = head->val;
delete head;
head = tmp;
--size;
return result;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int N;
cin >> N;
LinkedList* List = new LinkedList;
string input;
int val;
for (int i = 0; i < N; ++i) {
cin >> input;
if (input == "size") {
cout << List->getSize() << endl;
}
else if (input == "empty") {
cout << List->isEmpty() << endl;
}
else if (input == "top") {
cout << List->getTop() << endl;
}
else if (input == "push") {
cin >> val;
List->push(val);
}
else if (input == "pop") {
cout << List->pop() << endl;
}
}
return 0;
}
728x90