Repository navigation
Expand file tree
/
Copy pathLL.js
More file actions
125 lines (92 loc) · 2.24 KB
/
Copy pathLL.js
File metadata and controls
125 lines (92 loc) · 2.24 KB
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
117
118
119
120
121
122
123
124
125
var head;
class Node{
constructor(data, next = null){
this.data = data;
this.next = next
}
}
function printData(){
var n = head
while(n != null){
console.log(n.data+' ');
n = n.next;
}
}
function insertfirst(data){
var new_node = new Node(data);
new_node.next = head;
head = new_node;
}
//Since a Linked List is typically represented by the head of it,
//-we have to traverse the list till the end and then change the next to last node to a new node.
function insertLast(data){
var new_node = new Node(data);
if(head == null) new_node = head;// if head is empty new node becomes head
var last = head;
while(last.next != null){
last = last.next;
}
last.next = new_node;
new_node.next = null;
}
function insertBefore(some_node,data){
var new_node = new Node(data);
var before = head;
while(before.next != some_node)
{
before = before.next;
}
before.next = new_node;
new_node.next = some_node;
}
function insertAfter(some_node, data){
if(some_node == null){
console.log('no previous data');
return;
}
var new_node = new Node(data);
new_node.next = some_node.next;
some_node.next = new_node;
}
function removeNode(some_node){
var prev = head;
if(prev == some_node){
head = prev.next;
return;
}
while(prev.next != some_node){
prev = prev.next;
}
prev.next = some_node.next;
}
var head = new Node(1);
var second = new Node(2);
var third = new Node(3);
head.next = second;
second.next = third;
insertfirst(4);
insertAfter(second,5);
insertLast(0);
insertBefore(third,6);
printData();
removeNode(head);
console.log('---------------')
printData();
// class linkedList{
// constructor(head){
// this.head = new Node(head);
// this.size = 0;
// }
// insertData(value){
// while(value != null){
// value = value.next
// this.size ++;
// }
// }
// printData(){
// while(this.head != null){
// console.log(this.head.data+' ');
// this.head = this.head.next;
// }
// }
// }