
🖥️ JavaScript
// 노드 클래스 정의
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
// 단일 연결 리스트 클래스 정의
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
// 리스트 끝에 노드 추가
append(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
// 리스트의 첫 번째 노드 삭제
removeFirst() {
if (!this.head) return null;
const removedNode = this.head;
this.head = this.head.next;
this.length--;
if (this.length === 0) {
this.tail = null;
}
return removedNode.value;
}
// 리스트의 요소를 모두 출력
print() {
let current = this.head;
let result = [];
while (current) {
result.push(current.value);
current = current.next;
}
console.log(result.join(" -> "));
}
}
// 사용 예시
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.print(); // 출력: 10 -> 20 -> 30
list.removeFirst(); // 첫 번째 노드(10) 삭제
list.print(); // 출력: 20 -> 30
위 코드의 주요 포인트
Node 클래스 : 각각의 노드가 값과, 다음 노드를 가리키는 포인터를 가짐LinkedList 클래스 : 리스트의 삽입, 삭제, 출력 등의 메서드를 제공