Почему голова и хвост указывают на NULL после того, как выпал последний элемент в моем методе POP LinkedList Class в JSJavascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Почему голова и хвост указывают на NULL после того, как выпал последний элемент в моем методе POP LinkedList Class в JS

Сообщение Anonymous »

Я изучаю DSA для JS через Udemy. Я прибегал к тому, чтобы задать этот вопрос здесь и не направляться к Chatgpt, потому что я все еще старый в обучении и не убежден, что ИИ помогает в обучении, но просто делает нас ленивыми. Следовательно, я здесь, вы видите, что я сейчас изучаю ликовые списки, и я работаю эти примеры в редакторе Udemy. И я наткнулся на метод POP, так как я неоднократно провалился в их тестах. Мой код такой < /p>

Код: Выделить всё

class Node {
constructor(value) {
this.value = value;
this.next = null;

}
}
class LinkedList {
constructor(value) {
const newNode = new Node(value);
this.head = newNode;
this.tail = this.head;
this.length = 1;
}
printList() {
let temp = this.head;
while (temp !== null) {
console.log(temp.value);
temp = temp.next;

}
}
getHead() {
if (this.head === null) {
console.log("Head: null");
} else {
console.log("Head: " + this.head.value);
}
}
getTail() {
if (this.tail === null) {
console.log("Tail: null");
} else {
console.log("Tail: " + this.tail.value);
}
}
getLength() {
console.log("Length: " + this.length);
}
makeEmpty() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;

this.tail = newNode;
}
this.length++;
return this;
}
pop() {
let temp = this.head;
if (!this.head) {
return undefined;
}
let pre = temp;
while (temp.next) {
pre = temp;
temp = temp.next;

}
this.tail = pre;
this.tail.next = null;
temp.next = null;
this.length--;
return temp;
}
}

let myLinkedList = new LinkedList(1);

myLinkedList.push(2);
// (2) Items in LL - Returns 2 Node

if (myLinkedList.length !== 0) {
console.log(myLinkedList.pop().value);
} else {
console.log("null");
}

// (1) Item in LL - Returns 1 Node
if (myLinkedList.length !== 0) {
console.log(myLinkedList.pop().value);
} else {
console.log("null");
}

// (0) Items in LL - Returns null
if (myLinkedList.length !== 0) {
console.log(myLinkedList.pop().value);
} else {
console.log("null");
}
/*
EXPECTED OUTPUT:
----------------
2
1
null
*/
Неудачное тестов>

Подробнее здесь: https://stackoverflow.com/questions/796 ... -linkedlis
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»