-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list_book.js
116 lines (111 loc) · 2.16 KB
/
linked_list_book.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
106
107
108
109
110
111
112
113
114
115
116
class Node
{
constructor(data)
{
this.data = data;
}
}
class LinkedList
{
constructor(first_node)
{
this.first_node = first_node;
this.next_node = null;
}
reverse()
{
let reversedLL = new LinkedList();
let travellerNode = this.first_node;
while (true)
{
reversedLL.insertAtIndex(0, travellerNode.data);
if(!travellerNode.next_node)
{
break;
}
travellerNode = travellerNode.next_node;
}
this.first_node = reversedLL.first_node;
}
print()
{
let currentNode = this.first_node;
while(currentNode)
{
console.log(currentNode.data);
currentNode = currentNode.next_node;
}
}
read(index)
{
let currentIndex = 0;
let currentNode = this.first_node;
while(currentIndex < index)
{
if(currentNode.next_node)
{
currentNode = currentNode.next_node;
currentIndex++;
continue;
}
return -1;
}
return currentNode.data;
};
search(value)
{
let currentIndex = 0;
let currentNode = this.first_node;
while(currentNode.data != value)
{
if(currentNode.next_node)
{
currentNode = currentNode.next_node;
currentIndex++;
continue;
}
return -1;
}
return currentIndex;
}
insertAtIndex(index, value)
{
let currentIndex = 0;
let currentNode = this.first_node;
let nodeToInsert = new Node(value);
if(index === 0)
{
this.first_node = nodeToInsert;
nodeToInsert.next_node = currentNode;
return;
}
while(currentIndex < index - 1)
{
if(currentNode.next_node)
{
currentNode = currentNode.next_node;
currentIndex++;
continue;
}
return;
}
if(currentNode.next_node)
{
let nextToCurrent = currentNode.next_node;
nodeToInsert.next_node = nextToCurrent;
}
currentNode.next_node = nodeToInsert;
}
}
let node_1 = new Node("once");
let node_2 = new Node("upon");
let node_3 = new Node("a");
let node_4 = new Node("time");
node_1.next_node = node_2;
node_2.next_node = node_3;
node_3.next_node = node_4;
let list = new LinkedList(node_1);
list.print();
list.reverse();
console.log('------------');
list.print();