개발일지
[TS] 5. 객체지향 프로그래밍-Quiz 본문
22.09.07 목
- stack 구현 해보기
나의 답
interface Stack {
size: number;
push(str: string): void;
pop(): string;
}
class StackImpl implements Stack {
stackArr: string[];
size: number;
constructor(stackArr: string[]) {
this.stackArr = stackArr;
this.getHead();
}
private getHead(): number {
this.size = this.stackArr.length;
return this.size;
}
push(str: string): void {
this.stackArr[this.getHead()] = str;
}
pop(): string {
const result = this.stackArr[this.getHead() - 1];
delete this.stackArr[this.getHead() - 1];
return result;
}
}
const st = new Stack([]);
st.push('one');
st.push('two');
st.push('three');
console.log(st.stackArr);
console.log(st.pop());
console.log(st.stackArr);
정답
- head 개념 이용 하자
- 연결 리스트로 생각 해보기
interface Stack {
size: number;
push(value: string): void;
pop(): string;
}
type StackNode = {
readonly value: string;
readonly next?: StackNode;
};
class StackImpl implements Stack {
private _size: number = 0;
private head?: StackNode;
// getter
get size() {
return this._size;
}
push(value: string) {
const node: StackNode = {
value: value,
next: this.head,
};
this.head = node;
this._size++;
}
pop(): string {
// undefined는 null이 될 수 있다. (반대는 불가능!)
if (this.head == null) {
// undefined도 거를 수 있음!
throw new Error('Stack is empty!');
}
const node = this.head;
this.head = node.next;
this._size--;
return node.value;
}
}
참고) null vs undefined
- null == undefined / null !== undefined
- undefined는 null 개념에 포함 되지만 반대는 불가능
- 빈 값 처리 할 때 null로 두 타입 모두 거를 수 있음
'JS, TS > [TS | 강의] TS·OOP' 카테고리의 다른 글
[TS] 7. 제네릭-Quiz (0) | 2022.10.30 |
---|---|
[TS] 6. 제네릭 (0) | 2022.10.30 |
[TS] 4. 객체지향 프로그래밍 (0) | 2022.10.30 |
[TS] 3. 기본 타입-Quiz (0) | 2022.10.30 |
[TS] 2. 기본 타입 마스터 하기 (0) | 2022.10.30 |