LinkedList的實現目前我正在學習數據結構,我想實現在TS鏈表時面臨的幾個問題。我添加了幾個方法,但它似乎工作,輸出真的很奇怪。在打字稿
我的問題是在註釋中。
我的代碼:
function LinkedList() { //why doesn't fat arrow syntax work??
//ie. let LinkedList =() => {...this.append =() => {}...}
// prints out TypeError: t.append is not a function
let Node = (elem) => {
this.elem = elem;
this.next = null;
}
this.head = null;
this.len = 0;
this.append = (elem) => {
let node = new Node(elem);
let current;
if(this.head === null){
this.head = node;
} else {
current = this.head;
while(current.next){
current = current.next;
}
current.next = node;
}
this.len++;
}
this.removeAt = (pos) => {
if(pos > -1 && pos < this.len){
let current = this.head;
let previous;
let index = 0;
if(pos === 0){
this.head = current.next;
} else {
while(index++ < pos){
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.len--;
return current.elem;
} else {
return null;
}
}
this.insert = (elem, pos) => {
if(pos > -1 && pos < this.len){
let current = this.head;
let index = 0;
let previous;
let node = new Node(elem);
if(pos === 0){
node.next = current;
this.head = node;
} else {
while(index++ < pos){
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
this.len++;
return true;
} else {
return false;
}
}
this.toString =() => {
var current = this.head;
var str = '';
while(current){
str += current.elem; //output is undefinedundefinedundefined
// str += JSON.stringify(current);
// prints out {"next":{"next":{}}}{"next":{}}{}
current = current.next;
}
return str;
}
}
let t = new LinkedList();
t.append('asd'); //Doesn't work with fat arrow function declaration
t.append(1);
t.append(0);
console.log(t);
let tt = t.removeAt(1);
console.log(t,'tt', tt);
t.insert('asd',2);
let ttt = t.insert('a', 1)
console.log(ttt);
console.log(t);
console.log(t.toString());
是否有一個理由,爲什麼你不使用類? –