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() doesn't work I know exactly why !
- createPlayList() works because I used the copy i.e var current = playList; It has the same reference. Still it is working fine. I am confused how ? Which part of code or concept am I missing ?
- Also If I want to create doubly linked list using one more key 'prev' , using vanilla javascript ! Can I ?
Edited---------- Why createPlayList2() doesn't work ?
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");
Output -
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 !!.