class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
push(value) {
if (this.head === null) {
this.head = new Node(value);
this.tail = this.head;
this.size++;
return;
}
this.size++;
this.tail.next = new Node(value);
this.tail = this.tail.next;
}
pop() {
if (this.head === null) return;
if (this.head.next === null) {
this.head = null;
this.tail = null;
this.size--;
return;
}
let current = this.head;
while(current.next.next) {
current = current.next;
}
this.size--;
current.next = null;
this.tail = current;
}
isEmpty() {
return this.head === null ? true : false;
}
peek() {
if (this.head === null) return;
return this.tail.value;
}
get length() {
return this.size;
}
clear() {
this.head = null;
this.tail = null;
this.size = 0;
}
}
'자료구조' 카테고리의 다른 글
Deque란? (0) | 2022.06.27 |
---|---|
Queue란? (0) | 2022.06.27 |
연결리스트란? (단일 연결리스트, 이중 연결리스트, 원형 연결리스트) (0) | 2022.06.09 |
배열이란? (Array와 ArrayList의 차이) (0) | 2022.06.09 |