-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.js
106 lines (94 loc) · 2.06 KB
/
LinkedList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//linkedlist
class NewNode{
constructor(value){
this.value=value;
this.next=null;
}
}
class LinkedList{
constructor(value){
this.head={
value:value,
next:null
}
this.tail=this.head;
this.length=0;
}
append(value){
let newnode=new NewNode(value)
let currentnode=this.head
if (!currentnode){
this.head=newnode
this.length++;
}
this.tail.next=newnode;
this.tail=newnode;
this.length++;
return this
}
insert(index,value){
let currentnode=this.head
// console.log(currentnode)
let newnode=new NewNode(value)
//console.log(newnode)
while (currentnode){
//console.log("yes")
for (let i=0;i<=this.length;i++){
// console.log(i)
if (i===index-1){
let leader=currentnode
// console.log(leader)
//console.log("leader",leader)
let follower=leader.next
//console.log(follower)
leader.next=newnode;
newnode.next=follower;
}
else{
currentnode=currentnode.next;
//console.log("next",currentnode)
}
}
this.length++;
return this
}
}
prepend(value){
let follower=this.head
let newnode=new NewNode(value)
this.head=newnode;
this.head.next=follower;
this.length++;
return this;
}
remove(index){
let currentnode=this.head
// let newnode=new NewNode;
while (currentnode){
for (let i=0;i<this.length;i++){
if (i===index-1){
let leader=currentnode;
var follower=leader.next
leader.next=follower.next
currentnode=currentnode.next
}
this.length--;
return this;
}
}
printlist(){
let list=[]
let currentnode=this.head
while (currentnode){
list.push(currentnode.value)
currentnode=currentnode.next;
}
return list;
}
}
const linkedlist=new LinkedList(22)
linkedlist.append(12)
linkedlist.append(44)
linkedlist.append(30)
linkedlist.remove(1)
linkedlist.printlist()