linkedList prev와 tail 사용 후 o(1) 구현.
165
8 asked
class LinkedList {
length = 0;
head = null;
tail = null;
add(value) {
if (this.head) {
this.tail.next = new Node(value);
this.tail.next.prev = this.tail;
this.tail = this.tail.next;
} else {
this.head = new Node(value);
this.tail = this.head;
}
this.length++;
return this.length;
}
search(index) {
return this.#search(index)[1]?.value;
}
#search(index) {
let count = 0;
let prev;
let current = this.head;
while(count < index) {
prev = current;
current = current?.next;
count++;
}
return [prev, current];
}
remove(index) {
const [prev, current] = this.#search(index);
if (prev) {
prev.next = current.next;
this.length--;
return this.length;
} else if(current){ // index = 0 일 떄
current = current.next;
this.length--;
return this.length;
}
if (current.next === null) { // index = tail
this.tail = current.prev;
current.prev.next = null;
this.length--;
}
// 삭제 대상 없을 때 아무것도 안함.
}
}
class Node {
next = null;
prev = null;
constructor(value) {
this.value = value;
}
}
const li = new LinkedList();
li.add(1);
li.add(2);
li.add(3);
li.add(4);
li.add(5);
console.log(li.add(6));
console.log(li.remove(5));
console.log(li.remove(4));
console.log 찍었을때는 오류 없이 나온거 같은데 잘 구현 했나 궁금합니다!
Answer 1
1
index가 0부터 시작하는 게 아니라 1부터 시작하는 건가요?
그리고 next의 마지막에 4가 남아있습니다
1,2,3,4,5,6에서 4, 5를 지우는 걸 의도하신 거죠? 그러면 remove(4), remove(3)이 되어야 하는 게 아닌가싶습니다. 그리고 중간에 value 4인 node도 제거하셔야 하고, tail과의 연결도 끊어져있어서 다시 이어주셔야 합니다.
0
remove(index) {
const [prev, current] = this.#search(index);
if (prev && current) { // prev와 current 존재 중간 삭제
if (current.next === null) { // tail 부분 삭제
this.tail = current.prev;
this.tail.next = null;
} else {
prev.next = current.next;
current.next.prev = prev;
}
} else if (current === this.tail) { // index = 0, head 삭제
this.head = null;
this.tail = null;
}
this.length--;
return this.length;
}
li.add(1);
li.add(2);
li.add(3);
li.add(4);
li.add(5);
console.log(li.add(6));
console.log(li.remove(5));
console.log(li.remove(4));
console.log(li.remove(3));
console.log(li.remove(2));
console.log(li.remove(1));
console.log(li.remove(0));
console.log(li.remove(0));
remove() 부분을 다시 고쳐봤는데 어떤가요?
그리고 마지막에 remove(0)을 2번 반복했을떄 -1이 return 되는데 length에 조건이 없어서 그런건가요?
2주차 개념#12 트리 순회
0
14
2
프론트엔드 학습 수준 문의
0
22
2
백준 사이트 서비스 종료
0
38
3
잠겨버린 사물함 시간초과 관련 질문입니다.
0
17
1
스택, 큐 연결리스트로 구현 과제 완료입니다!
0
93
1
heapify 안의 bigger 삼항연산자 질문
0
116
2
LinkedList로 스택, 큐 구현하기 숙제
0
123
1
숙제 : LinkedList로 Stack, Queue 구현하기
0
177
1
연결리스트 숙제
0
239
1
한번에 이해 안가는 제가 비정상 일까요...?
0
234
1
우선순위 큐 질문이 있습니다!
0
154
1
[숙제] minHeap 구현, maxHeap -> minHeap , minHeap -> maxHeap
1
235
1
최소힙 remove 구현하기
0
245
1
숙제 최소힙 만들기
0
152
1
숙제 length return 하기
0
194
1
숙제 : 같은 값을 넣은경우 에러 처리
0
181
1
영상 중간에 0:10 1:23초 수정에 따른 코드 최종본
1
143
1
숙제2 연결리스트를 이용하여 큐 구현하기
0
237
1
숙제1 LinkedList로 스택 구현하기
1
251
1
연결 리스트 구현 숙제 리뷰 부탁드려봅니다
1
345
2
let current = this.head 질문 있습니다!
0
251
1
퀴즈 답안
0
469
1
최소힙의 결과값과 최대힙->최소힙 결과값이 다른게 맞나요?
0
248
1
1주차 숙제에 대한 해답 코드는 따로 제공되지 않나요??
0
495
1

