-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.js
105 lines (94 loc) · 2.14 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
//10-->5-->6
class linkedList{
constructor(value){
this.head={
value:value,
next:null
}
this.tail=this.head
this.length=1
}
append(item){
const newNode={
value:item,
next:null
}
this.tail.next=newNode
this.tail=newNode
this.length++
}
prepend(item){
const newNode={
value:item,
next:this.head
}
this.head=newNode
this.length++
}
printList(){
const print =[]
let currentNode=this.head
while(currentNode !==null){
print.push(currentNode.value)
currentNode=currentNode.next
}
return print
}
insert(index,value){
const newNode={
value:value,
next:null
}
let count=0
let currentNode=this.head
if(index>=this.length){
this.append(value)
}
else if(index==0){
this.prepend(value)
}
else{
while(count<index-1){
currentNode=currentNode.next
count++
}
let rightNodes = currentNode.next
newNode.next=rightNodes
currentNode.next=newNode
}
}
deleteNode(index){
if(index>=this.length){
console.log("no node exist");
}
else if(index==0){
this.head=this.head.next
this.length--
}
else{
let currentNode=this.head
let count=0
while(count<=index-1){
currentNode=currentNode.next
count++
}
let leftNodes = currentNode
let nodeToDelete =currentNode.next
let rightNodes= nodeToDelete.next
leftNodes.next=rightNodes
this.length--
}
}
reverseLinklist(){
}
}
let linklist= new linkedList(10)
linklist.append(5)
linklist.append(16)
linklist.append(1)
linklist.prepend(9)
linklist.insert(19,900)
linklist.insert(0,700)
linklist.deleteNode(0)
linklist.reverseLinklist()
console.log(linklist.printList());