class Stack {
top = null;
length = 0;
push(value){
const newNode = new Node(value); //new Node 생성 후 할당
newNode.next = this.top; //new Node의 next는 현재 top
this.top = newNode; //top을 new Node로 재할당
this.length++;
return this.length;
}
pop(){
if(!this.top){
return null;
}
this.top = this.top.next; //top은 현재 top의 next
this.length--;
return this.length;
}
top(){
return this.top.value;
}
}
class Node{
next = null;
constructor(value){
this.value = value;
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.pop();
stack.pop();
스택은 뒤로 넣고 뒤로만 뺄 수 있다. 프링글스를 생각하면 된다.
top이라는 것을 통해 스택의 마지막 요소를 알 수있다.
시간복잡도는 새로운 값을 넣는데는 O(1), 빼는데 O(1), 제일 위에 값을 확인하는데 O(1)이다.
공간 복잡도는 O(n)이다.
'자료구조' 카테고리의 다른 글
연결 리스트(Linked List) (0) | 2024.04.23 |
---|---|
BFS, DFS, Tree traversal - Javascript 구현 (1) | 2024.02.20 |
Javascript로 이진탐색트리 구현하기 (1) | 2024.02.12 |
Javascript로 Queue 구현하기 (0) | 2024.02.12 |
Javascript LinkedList 만들기 (0) | 2024.02.12 |