-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathinsert_in_sorted_ll.js
More file actions
57 lines (49 loc) · 1.54 KB
/
insert_in_sorted_ll.js
File metadata and controls
57 lines (49 loc) · 1.54 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
/**
* Node class represents a node in a linked list.
* @param {any} value - The value of the node.
*/
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
/**
* Linked List class represents a sorted linked list.
*/
class LL {
constructor() {
this.head = null;
}
/**
* Adds a new node with the specified value in a sorted manner in the linked list.
* @param {any} value - The value to be added to the linked list.
*
* Time Complexity: O(n) - where n is the number of nodes in the linked list.
* In the worst case, it may need to traverse the entire list to find the correct position.
* Space Complexity: O(1) - constant space, no additional data structures used.
*/
add(value) {
let newNode = new Node(value);
let tempHead = this.head;
// If the list is empty or the new node's value is smaller than the head's value
if (this.head === null || this.head.value >= newNode.value) {
newNode.next = this.head;
this.head = newNode;
} else {
// Traverse the list to find the correct position for the new node
while (tempHead.next != null && tempHead.next.value < newNode.value) {
tempHead = tempHead.next;
}
// Insert the new node in the sorted position
newNode.next = tempHead.next;
tempHead.next = newNode;
}
}
}
// Example usage
let ll = new LL();
ll.add(3);
ll.add(5);
ll.add(4);
console.log(ll);