我有一个反向链接列表,该列表不返回头。列表打印出来。但是,当我在其他函数中使用它时,我无法访问countList函数中链表的开头。我试过使用head.prev,但这也不起作用。我正在尝试使用反向链接列表的节点中的所有字母创建一个字符串。
class Node{
constructor(data, next = null){
this.data = data;
this.next = next;
}
}
class LinkedList{
constructor(){
this.head = null;
}
insertLast(value){
if(this.head === null){
this.head = new Node(value);
}else{
let node = this.head;
while(node.next){
node = node.next;
}
node.next = new Node(value);
}
}
}//constructor end
let listOne = new LinkedList();
let listTwo = new LinkedList();
listOne.insertLast(5);
listOne.insertLast(4);
listOne.insertLast(2);
listTwo.insertLast(7);
listTwo.insertLast(9);
listTwo.insertLast(1);
console.log(listOne);
const countList = function(list){
console.log('here is the list in coutnlist', list);
let curr = list.head;
console.log("this is curr ", curr);
// let str = '';
while(curr.next){
curr = curr.next;
str+=curr.data;
}
return str;
}
const sumLists = function(listOne, listTwo){
let reverse1 = reverse(listOne);
console.log('thisi s reverse 1', reverse1)
let reverse2 = reverse(listTwo);
let firstNum = countList(reverse1);
let secondNum = countList(reverse2);
console.log('this is first num', firstNum);
let finalNum = parseInt(firstNum + secondNum);
return finalNum;
}
const reverse = function(list){
let curr = list.head;
let prev = null;
let temp = null;
while(curr){
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
console.log(sumLists(listOne, listTwo));