단일 연결 리스트(Singly Linked List)
0. 요약
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.rear = null;
this.size = 0;
}
// 단일 연결 리스트 맨 앞에 원소 추가하기
unshift(data) {
const node = new Node(data);
if (!this.head) this.rear = node;
node.next = this.head;
this.head = node;
this.size += 1;
return this;
}
// 단일 연결 리스트 맨 뒤에 원소 추가하기
push(data) {
const node = new Node(data);
if (this.size === 0) this.head = node;
else this.rear.next = node;
this.rear = node;
this.size++;
return this;
}
// 단일 연결 리스트 중간에 원소 추가하기
insert(index, data) {
if (index < 0 || index > this.size) return false;
if (index === 0) return !!this.unshift(data);
if (index === this.size) return !!this.push(data);
const node = new Node(data);
let prev = this.get(index - 1);
node.next = prev.next;
prev.next = node;
this.size += 1;
return true;
}
// 단일 연결 리스트의 원소 가져오기
get(index) {
if (index < 0 || index >= this.size) return null;
if (index === this.size - 1) return this.rear;
let cur = this.head;
let count = 0;
while (count < index) {
cur = cur.next;
count += 1;
}
return cur;
}
// 단일 연결 리스트의 첫번째 원소 삭제하기
shift() {
if (!this.head) return undefined;
const currentHead = this.head;
this.head = currentHead.next;
this.size -= 1;
if (this.size === 0) this.rear = null;
return currentHead;
}
// 단일 연결 리스트의 마지막 원소 삭제하기
pop() {
if (!this.head) return undefined;
let current = this.head;
let newRear = current;
while (current.next) {
newRear = current;
current = current.next;
}
newRear.next = null;
this.rear = newRear;
this.size -= 1;
if (this.size === 0) {
this.head = null;
this.rear = null;
}
return current;
}
// 단일 연결 리스트의 중간 원소 삭제하기
insert(index, data) {
if (index < 0 || index > this.size) return false;
if (index === 0) return !!this.unshift(data);
if (index === this.size) return !!this.push(data);
const node = new Node(data);
let prev = this.get(index - 1);
node.next = prev.next;
prev.next = node;
this.size += 1;
return true;
}
// 단일 연결 리스트 초기화하기
clearList() {
this.head = null;
this.rear = null;
this.size = 0;
}
// 단일 연결 리스트의 모든 원소 출력하기
printListData() {
let cur = this.head;
while (cur) {
console.log(cur);
cur = cur.next;
}
}
// 단일 연결 리스트 역순으로 바꾸기
reverse() {
let head = this.head;
let rear = this.rear;
this.head = rear;
this.rear = head;
let prev = this.rear;
let cur = this.rear.next;
let count = 0;
while (count < this.size - 1) {
const temp = cur.next;
cur.next = prev;
cur = temp;
prev = cur;
count += 1;
}
this.rear.next = null;
return this;
}
}1. 개요
2. 연결 리스트란?
3. 자바스크립트로 단일 연결 리스트 구현하기
3-1. 노드와 연결 리스트의 기본 구조
3-2. 연결 리스트에 원소 추가하기
3-3. 연결 리스트의 원소 가져오기
3-4. 연결 리스트의 원소 업데이트하기
3-5. 연결 리스트의 원소 삭제하기
3-6. 연결 리스트 초기화하기
3-7. 연결 리스트의 모든 원소 출력하기
3-8. 연결 리스트 역순으로 바꾸기
4. 시간 복잡도
Insertion
Removal
Searching
Access
5. Conclusion
출처
Last updated