使用JavaScript而不使用类语法的链表


let playlist_data = ["Reset","I believe","Whatever it takes","Never Enough For me","Do you Remember"];
function createNode(data="",next=null,prev=null){
this.data = data;
this.next = next;
}
function createPlayList(playlist_data,len){
var arr = playlist_data;
var playList = null;
for(let i=0;i<len;i++){
if(playList === null){
playList = new createNode(arr[i]);
}
else {
var current = playList;
while(current.next !== null){
current = current.next;
}
current.next = new createNode(arr[i]);           
}
}
return playList;
}
console.log(createPlayList(playlist_data,playlist_data.length));

function createPlayList2(playlist_data,len){
var arr = playlist_data;
var playList = null;
for(let i=0;i<len;i++){
if(playList === null){
playList = new createNode(arr[i]);
}
else {
//var current = playList;
while(playList.next !== null){
playList = playList.next;
}
playList.next = new createNode(arr[i]);  
}
}
return playList;
}
  • createPlayList2((不起作用我知道为什么
  • createPlayList((之所以有效,是因为我使用了副本,即var current=playList;它有相同的参考。尽管如此,它仍然运行良好。我怎么搞糊涂了?我缺少代码或概念的哪一部分
  • 此外,如果我想使用一个键"prev"创建双链接列表,请使用香草javascript!我可以吗

已编辑-------为什么createPlayList2((不起作用?

function createPlayList(playlist_data,len){
var arr = playlist_data;
var playList = null;
for(let i=0;i<len;i++){
if(playList === null){
console.log("Null PlayList");
playList = new createNode(arr[i]);
}
else {
//var current = playList;
console.log("Before Traversing");
console.log(playList);
while(playList.next !== null){
playList = playList.next;
console.log("Traversing");
console.log(playList);
}
playList.next = new createNode(arr[i]);
console.log("After Traversing");
console.log(playList); 
}
}
return playList;
}
console.log("Called Funtion");
console.log(createPlayList(playlist_data,playlist_data.length))
console.log("Ends");

输出-

Called Function
Null PlayList // when playList is empty at i=0
Before Traversing // when playlist is not empty at i=1
{data: "Reset", next: null} // current playList value
After Traversing // after while loop
{data: "Reset", next:{data: "I believe",next: null}} 
Before Traversing // at i=2
{data: "Reset", next:{data: "I believe",next: null}} // current PlayList
Traversing // inside while loop
 {data: "I believe", next: null} // current playList changes to this !
========================.............
Rest the loop continues, I have changed the original value of playList while traversing. The reason it is not working !!.

不同之处在于,在第二个版本中,即使playList已经指向列表的第一个节点,也可以为其指定一个新值。您应该分配给playList的唯一时间是当列表为空时。因此,您的第二个代码将用于添加第一个元素。但是,如果添加第二个元素,则最终会使playList指向该新节点,因此;丢失";最初的第一个节点——现在没有任何内容引用该节点。

原则是,一旦将playList初始化为列表中的第一个节点,就不应该更改它,当然,除非您想删除列表中的首个节点。

第一个版本是正确的,因为它使用了另一个(临时(变量来遍历列表,而不影响playList

相关内容

  • 没有找到相关文章