pop() {
if (!this.head) return undefined;
let current = this.head;
let newTail = current;
// 현재 node의 next node가 있을 때까지 반복
while (current.next) {
// 다음 node가 있다면
// 현재 node를 newTail로 할당
newTail = current;
// 현재 node의 next를 현재 node로 할당
current = current.next;
}
// 다음 node가 없다면 newTail을 this.tail에 할당
this.tail = newTail;
// this.tail의 다음 node를 null로 설정함으로써
// 1. 이후에 아무것도 없다고 알려주고
// 2. '!'에 대한 연결을 끊는다
this.tail.next = null;
this.length--;
// head만 남은 상황에서 pop 메서드를 사용하면 head, tail 모두 null
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}
// pop 메서드
// list.pop()
// > Node {val: '!', next: null}
// list.pop()
// > Node {val: 'goodbye', next: null}
// list.pop()
// > Node {val: 'hello', next: null}
// list.pop() undefined