链表实现上的 toString 方法在 js 中不起作用



我正在通过破解编码面试,我想我会在 JS 5 中实现所有数据结构。 谁能向我解释为什么我的 toString 方法不起作用?

谢谢!

    function Node(data) {
    	this.next = null;
      this.data = data;
    }
    
    Node.prototype.appendToTail = function(data) {
    	var end = new Node(data);
      var n = this;
      while (n.next != null) {
      	n = n.next;
      }
      n.next = end;
    }
    
    Node.prototype.toString = function(head) {
    	
    	console.log(head)
    
    	if (head == null) {
      	return ""
      } else {
    	  return head.data.toString() + "-> " + head.next.toString();
      }
    	
    }
    
    var ll = new Node(1);
    ll.appendToTail(3);
    ll.appendToTail(4);
    
    console.log(ll.toString())

function Node(data) {
    this.next = null;
  this.data = data;
}
Node.prototype.appendToTail = function(data) {
  var end = new Node(data);
  var n = this;
  while (n.next != null) {
    n = n.next;
  }
  n.next = end;
};
Node.prototype.toString = function() {
    var returnValue = String(this.data);
    if (this.next) {
        returnValue = returnValue + "-> " + String(this.next); 
    }
    return returnValue;
};
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(String(ll))

或者完全避免这类问题,不要使用原型、类、这个、调用等

您的toString函数接受一个参数,但在调用 toString 时没有传递它。

如果要访问节点,则应使用 this ,而不是传入值

Node.prototype.toString = function() {
   var result = this.data.toString();
   if (this.next) {
     result += "-> " + this.next.toString();
   }
   return result;
}

最新更新