연결 목록에서 요소를 제거하는 것은 매우 쉽습니다. 제거하려는 노드를 제거하기만 하면 됩니다. 즉, 참조를 잃게 됩니다. 우리가 고려해야 할 3가지 경우가 있습니다 -
- head에서 요소 제거:이 경우 head =head.next를 간단히 할당할 수 있습니다. 이렇게 하면 첫 번째 요소의 참조를 잃게 됩니다. 그리고 out head는 두 번째 요소를 가리키기 시작할 것입니다.
- 꼬리에서 요소 제거:이 경우 두 번째 마지막 노드의 node.next를 null로 지정하기만 하면 목록에서 마지막 요소를 제거할 수 있습니다.
- 사이에서 요소 제거:이것은 더 까다롭습니다. 이 경우 제거하려는 노드 앞에 노드를 만들어 제거하려는 노드 뒤의 노드를 직접 가리키도록 해야 합니다. 따라서 prevNode.next =node.next가 이 작업을 수행합니다.
이제 이에 대한 예시를 살펴보겠습니다 -

이제 이것을 구현하는 방법을 살펴보겠습니다 -
예시
remove(data, position = 0) {
if (this.length === 0) {
console.log("List is already empty");
return;
}
this.length--;
let currNode = this.head;
// Condition 1
if (position <= 0) {
this.head = this.head.next;
}
// Condition 2
else if (position >= this.length - 1) {
while (currNode.next.next != null) {
currNode = currNode.next;
}
currNode.next = null;
}
// Condition 3
else {
let iter = 0;
while (iter < position) {
currNode = currNode.next; iter++;
}
currNode.next = currNode.next.next;
}
} −
를 사용하여 이것을 테스트할 수 있습니다.예시
let list = new LinkedList(); list.insert(10); list.insert(20); list.insert(30); list.remove(1); list.display(); list.insert(15, 2); list.remove(); list.display();
출력
이것은 출력을 줄 것입니다 -
20 -> 30 -> 30 -> 15 ->