음악을 듣다보면 되감기이나 다음 트렉 버튼을 볼 수 있습니다.
이 기능이 작동할 수 있는 이유는 각 버튼에 이전, 혹은 다음 곡들의 요소가 서로 연결되어있기 때문입니다.
이렇게 요소들이 일정한 방향을 기준으로 서로 연결되어있는 자료구조가 linked list입니다.
(여기서는 singly-Linked list를 설명합니다.)
Linked list는 노드(node)로 구성되어있습니다.
노드에는 value과 next값이 존재합니다. 그 중에서는 next에는 다음 node의 값이 할당되면서 다음 노드와 현재 노드가 연결되게 됩니다.
(출처 : https://www.softwaretestinghelp.com/linked-list/)
가장 앞의 node는 head이며 가장 마지막 node(next값이 null)는 tail이 됩니다.
1) 배열
배열은 원래는 처음 선언할 때 크기를 고정해야 합니다 (변경이 불가능)
=> 그래서 배열은 정적 구조라고 합니다.
자바스크립트에서 배열의 크기가 변하는 이유는 자바스크립트가 사기라서...
배열에서는 요소를 추가하기 위해서는 요소 뒤의 요소를 모두 뒤로 이동해야 합니다.
요소를 제거하기 위해서는 제거 후에 요소를 전부 앞으로 이동해야 합니다.
따라서 제거와 추가에 매우 비효율적입니다.
대신 index값만 가지고 있으면 자료추적이 매우 빠릅니다.
ex) arr[0] , arr[3]
2) Linked list
반면에 Linked list는 node만 추가하면 크기는 계속 변할 수 있으므로 동적 구조라고 불립니다.
노드를 추가하기 위해서는 원하는 위치 이전 노드와 다음 노드 사이에 추가를 하고 서로를 연결하면 됩니다.
제거하기 위해서는 이전 노드와 다음 노드만 서로 연결해주면 해당 노드는 연결점이 없어져서 제거가 됩니다.
=>노드 제거 원리
(출처 : https://stackoverflow.com/questions/41474163/singly-linked-list-remove)
반면에 자료를 참조하기 위해서는 head부터 next를 통해 추적해야 하므로 자료를 찾는 속도가 매우 느리다.
=> 한 장 요약
(출처 : https://opentutorials.org/module/1335/8636)
Linked-list는 노드로 구성되어있다.
//노드 생성하는 함수
function Node(value) {
this.data = value;
this.next = null;
};
또한 Linked-list는 head와 tail이 존재한다
function LinkedList() {
this._size = 0;
this.head = null;
this.tail = null;
};
여기에 size를 하나씩 추가한다.
LinkedList.prototype.addToTail = function(value){
let node = new Node(value);
if(!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this._size++;
return node;
}
이때 사이즈는 1개 줄여준다.
LinkedList.prototype.remove = function(data){
if(!this.head) {
return undefined;
}
if (this.head.data === data) {
this.head = this.head.next;
return this;
}
let preNode = this.head;
let nextNode = this.head.next;
while(preNode) {
if(nextNode.data === data) {
break;
}
preNode = nextNode;
nextNode = nextNode.next;
}
preNode.next = nextNode.next;
this._size--;
return this;
}
LinkedList.prototype.getValue = function(index){
let result = this.head;
if(index > this._size) {
return undefined;
}
for(let i = 0; i < index; i++) {
result = result.next;
}
return result;
}
Linkedlist.prototype.contains = function(value){
let result = this.head;
while(result){
if(result.value === value){
return true;
}
result = result.next;
}
return false;
};
LinkedList.prototype.indexof = function(value){
let result = this.head;
let count = 0;
while(result){
if(result.value === value){
return count;
}
result = result.next;
count++;
}
return -1;
};
LinkedList.prototype.size = function(){
return this._size;
};