리스트의 개념을 가볍게 훑고
타입스크립트로 리스트 스택을 구현해 볼 것 입니다.
class Node<T> {
private data: T;
link: Node<T> | null | undefined;
constructor(value: T, link: Node<T> | null | undefined) {
this.data = value;
this.link = link;
}
public getData(): T {
return this.data;
}
}
class Stack<T> {
private top: Node<T> | null | undefined;
constructor() {
this.top = null;
}
isEmpty(): boolean {
return this.top === null;
}
push(value: T): void {
const newNode = new Node(value, this.top);
this.top = newNode;
}
pop(): T | null | undefined {
if (this.isEmpty()) {
throw new Error("스택이 비어있습니다.");
}
const returnNode = this.top;
this.top = returnNode?.link;
return returnNode ? returnNode.getData() : null;
}
}
테스트
const stack = new Stack();
try {
stack.pop();
} catch (e) {
console.log(e);
}
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
결과
Error: 스택이 비어있습니다.
3
2
1
```![](https://velog.velcdn.com/images/kcdmlry/post/3a86eb67-002c-498b-bd16-badd01af9699/image.png)