문제
연결 리스트의 헤드를 첫 번째이자 유일한 인수로 취하는 JavaScript 함수를 작성해야 합니다.
우리 함수는 목록의 가장 중간 노드에 저장된 값을 반환해야 합니다. 그리고 가장 중간에 두 개의 노드가 있으면 그 중 두 번째 노드를 반환해야 합니다.
예를 들어 목록이 다음과 같은 경우:
입력
[4, 6, 8, 9, 1]
출력
const output = 8;
다음은 코드입니다:
예시
class Node {
constructor(data) {
this.data = data;
this.next = null;
};
};
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
};
};
LinkedList.prototype.add = function(data) {
const newNode = new Node(data);
let curr;
if(this.head === null) {
this.head = newNode;
} else {
curr = this.head;
while(curr.next) {
curr = curr.next;
}
curr.next = newNode;
};
this.size++;
};
const list = new LinkedList();
list.add(4);
list.add(6);
list.add(8);
list.add(9);
list.add(1);
const findMiddle = (head) => {
let slow = head
let fast = head
while(fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow.data
};
console.log(findMiddle(list.head)); 출력
8