연결리스트는 각 노드가 오직 한 방향(다음 노드)으로만 연결되어 있는 선형 자료구조
각 노드는 두 가지 정보를 가짐.
리스트의 시작은 헤드(Head) 노드로, 끝은 null(혹은 None)로 표시함.
[Head] -> [Node1] -> [Node2] -> [Node3] -> null
이런 한계를 극복하기 위해 이중 연결리스트(Doubly Linked List), 원형 연결리스트(Circular Linked List) 등이 고안됨.
// Node() : data와 point를 가지고 있는 객체
function Node(data) {
this.data = data;
this.next = null;
}
// LinkedList(): head와 length를 가지고 있는 객체
function LinkedList() {
this.head = null;
this.length = 0;
}
// size() : 연결 리스트 내 노드 개수 확인
LinkedList.prototype.size = function () {
return this.length;
}
// isEmpty() : 객체 내 노드 존재 여부 파악
LinkedList.prototype.isEmpty = function () {
return this.length === 0;
}
// printNode() : 노드 출력
LinkedList.prototype.printNode = function () {
for (let node = this.head; node != null; node = node.next) {
process.stdout.write(`${node.data} -> `);
}
console.log("null");
}
// append() : 연결 리스트 가장 끝에 노드 추가
LinkedList.prototype.append = function (value) {
let node = new Node(value),
current = this.head;
if (this.head === null) {
this.head = node;
} else {
while (current.next != null) {
current = current.next;
}
current.next = node;
}
this.length++;
};
// insert() : position 위치에 노드 추가
LinkedList.prototype.insert = function (value, position = 0) {
if (position < 0 || position > this.length) {
return false;
}
let node = new Node(value),
current = this.head,
index = 0,
prev;
if (position == 0) {
node.next = current;
this.head = node;
} else {
while (index++ < position) {
prev = current;
current = current.next;
}
node.next = current;
prev.next = node;
}
this.length++;
return true;
};
// remove() : value 데이터를 찾아 노드 삭제
LinkedList.prototype.remove = function (value) {
let current = this.head,
prev = current;
while (current.data != value && current.next != null) {
prev = current;
current = current.next;
}
if (current.data != value) {
return null;
}
if (current === this.head) {
this.head = current.next;
} else {
prev.next = current.next;
}
this.length--;
return current.data;
};
// removeAt() : position 위치 노드 삭제
LinkedList.prototype.removeAt = function (position = 0) {
if (position < 0 || position >= this.length) {
return null;
}
let current = this.head,
index = 0,
prev;
if (position == 0) {
this.head = current.next;
} else {
while (index++ < position) {
prev = current;
current = current.next;
}
prev.next = current.next;
}
this.length--;
return current.data;
}
// indexOf() : value 값을 갖는 노드 위치 반환
LinkedList.prototype.indexOf = function (value) {
let current = this.head,
index = 0;
while (current != null) {
if (current.data === value) {
return index;
}
index++;
current = current.next;
}
return -1;
}
// remove2() : indexOf + removeAt = remove
LinkedList.prototype.remove2 = function (value) {
let index = this.indexOf(value);
return this.removeAt(index);
};