스택(Stack)은 "쌓다"라는 의미로, 데이터를 차곡차곡 쌓아 올린 형태의 자료구조 입니다.
Last In First Out
getTop() : O(1)
push() : O(1)
pop() : O(1)
(2023-week3-p3)
class Node {
private:
int value;
Node *next;
public:
Node(int value);
void setNext(Node *next);
Node *getNext();
int getValue();
friend class LinkedList;
};
class LinkedList {
private:
Node *head;
Node *tail;
int size;
public:
LinkedList();
bool empty();
void increaseSize();
void decreaseSize();
int getSize();
void addFront(int value);
void removeFront();
friend class Stack;
};
class Stack {
private:
Node *top; // 제일 위에 있는 애를 가리키는 포인터 변수
LinkedList *stackList; // 단일 연결 리스트로 구현
public:
Stack();
int getSize();
bool empty();
int getTop();
void updateTop();
void push(int x);
int pop();
};
Stack::Stack() {
stackList = new LinkedList();
top = stackList->head;
// top은 단일연결리스트의 head
}
int Stack::getSize() {
return stackList->getSize();
}
bool Stack::empty() {
return getSize() == 0;
}
void Stack::updateTop() {
top = stackList->head;
}
int Stack::getTop() {
if (empty()) {
return -1;
}
return top->getValue();
}
void Stack::push(int x) {
stackList->addFront(x);
updateTop();
}
int Stack::pop() {
if (empty()) {
return -1;
}
int poppedValue = getTop();
stackList->removeFront();
updateTop();
return poppedValue;
}
단일 연결리스트를 제대로 작성했다면 어려울게 없습니다.
전체 코드
https://github.com/Landvibe-DataStructure-2024/StudyNotes/tree/main/w03
연결리스트를 활용한 간단한 구현방법
배열로 구현한 제일 간단한 구현방법