[英]Remove elements from a Linked List
為什么我的解決方案不適用於這個 freecodecamp 問題? 失敗的測試是:
this.remove = function(element){
// Only change code below this line
if (head.element === element){
head = head.next;
length--;
return;
}
let p = head;
while(p){
p = p.next;
if (p.next.element === element)
{
p.next = p.next.next;
length--;
return;
}
}
return;
// Only change code above this line
};
讓我們假設代碼的結構與freecodecamp上的原始問題相同。
你的錯誤:循環應該從p
而不是p.next
開始
function LinkedList() { var length = 0; var head = null; var Node = function(element) { this.element = element; this.next = null; }; this.size = function() { return length; }; this.head = function() { return head; }; this.add = function(element) { var node = new Node(element); if (head === null) { head = node; } else { var currentNode = head; while (currentNode.next) { currentNode = currentNode.next; } currentNode.next = node; } length++; }; this.remove = function(element) { // Only change code below this line if (head.element === element) { head = head.next; length--; return; } let p = head; while (p) { if (p.next && p.next.element === element) { p.next = p.next.next; length--; return; } else { p = p.next; } } return; // Only change code above this line }; } console.assert( (function() { var test = new LinkedList(); return typeof test.remove === 'function'; })() ); console.assert( (function() { var test = new LinkedList(); test.add('cat'); test.add('dog'); test.remove('cat'); return test.head().element === 'dog'; })() ); console.assert( (function() { var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('hamster'); test.remove('cat'); test.remove('fish'); return test.size() === 2; })() ); console.assert( (function() { var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('snake'); test.add('kitten'); test.remove('snake'); return test.head().next.next.element === 'kitten'; })() ); console.assert( (function() { var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('kitten'); test.remove('elephant'); return ( JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}' ); })() ); console.log("all assertions passed");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.