現在、データ構造を学習しており、TSでLinkedListを実装しようとするといくつかの問題に直面しています。いくつかの方法を追加しましたが、うまくいくようですが、出力は本当に奇妙です。TypedScriptのLinkedList実装
私の質問はコメントです。
私のコードは:
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());
ありますか? –