이 포스팅은 드림코딩 엘리님의 타입스크립트 강의를 복습하며 작성되었습니다. 전체 코드는 포스팅 최하단에 있습니다.
단일 연결 리스트를 이용해 스택을 구현
interface Stack {
readonly size: number;
push(value: string): void;
pop(): string;
}
stack에 들어갈 노드의 값 = value
value가 가리키는 다음 노드 = next
type StackNode = {
readonly value: string;
readonly next?: StackNode;
};
readonly
next?: StackNode;
: Interface 규격에 맞게 stack을 구현한다.
(Impl : Implementation)
private _size: number = 0;
스택 사이즈 0부터 시작
(참고) readonly _size (X)
: class안에서도readonly
를 붙이면 _size를 변경할 수 없다.
constructor로 스택의 크기를 지정한다.
class StackImpl implements Stack {
private _size: number = 0;
private head?: StackNode;
constructor(private capacity: number) {}
size
를 정의한다.size
정보를 읽기만 가능하다. 내부에서는 변경 가능하다. get size() {
return this._size;
}
push(value: string): void {
if (this.size === this.capacity) {
throw new Error("Stack is already full!");
}
const newNode: StackNode = { value, next: this.head };
this.head = newNode;
this._size++;
}
pop(): string {
if (this.head == null) {
throw new Error("Stack is empty!");
}
const nodeToPop = this.head;
this.head = nodeToPop.next;
this._size--;
return nodeToPop.value;
}
⚠️ 왜 null? - null또는 undefined가 들어올 경우 대비해서
null == undefined
null !== undefined
interface Stack {
readonly size: number;
push(value: string): void;
pop(): string;
}
type StackNode = {
readonly value: string;
readonly next?: StackNode;
};
// Stack interface를 구현하는 StackImpl 클래스
class StackImpl implements Stack {
private _size: number = 0; // 스택 사이즈 0부터 시작
private head?: StackNode;
// 스택 사이즈 지정
constructor(private capacity: number) {}
get size() {
return this._size;
}
push(value: string): void {
if (this.size === this.capacity) {
throw new Error("Stack is full!");
}
const node: StackNode = { value, next: this.head };
// 새로 들어온 node는 head가 기존에 가리키던 노드를 가리키도록 함
this.head = node;
// head는 새로 들어온 node를 가리키도록 변경
this._size++;
}
pop(): string {
if (this.head == null) {
throw new Error("Stack is empty!");
}
const node = this.head;
this.head = node.next;
this._size--;
return node.value;
}
}