Sponsored
Sponsored
In this approach, you will design a singly linked list where each node has a value and a pointer to the next node. This type of list is simple and efficient for certain operations, especially when traversing only forwards is sufficient.
Time Complexity:
- get
: O(n)
- addAtHead
: O(1)
- addAtTail
: O(n)
- addAtIndex
: O(n)
- deleteAtIndex
: O(n)
Space Complexity: O(n), where n is the number of nodes in the list.
1class Node {
2 constructor(val) {
3 this.val = val;
4 this.next = null;
5 }
6}
7
8class MyLinkedList {
9 constructor() {
10 this.head = null;
11 }
12
13 get(index) {
14 let current = this.head;
15 for (let i = 0; i < index; i++) {
16 if (!current) return -1;
17 current = current.next;
18 }
19 return current ? current.val : -1;
20 }
21
22 addAtHead(val) {
23 const node = new Node(val);
24 node.next = this.head;
25 this.head = node;
26 }
27
28 addAtTail(val) {
29 const node = new Node(val);
30 if (!this.head) {
31 this.head = node;
32 return;
33 }
34 let current = this.head;
35 while (current.next) {
36 current = current.next;
37 }
38 current.next = node;
39 }
40
41 addAtIndex(index, val) {
42 if (index === 0) {
43 this.addAtHead(val);
44 return;
45 }
46 let current = this.head;
47 for (let i = 0; i < index - 1; i++) {
48 if (!current) return;
49 current = current.next;
50 }
51 if (current) {
52 const node = new Node(val);
53 node.next = current.next;
54 current.next = node;
55 }
56 }
57
58 deleteAtIndex(index) {
59 if (index === 0 && this.head) {
60 this.head = this.head.next;
61 return;
62 }
63 let current = this.head;
64 for (let i = 0; i < index - 1 && current; i++) {
65 current = current.next;
66 }
67 if (current && current.next) {
68 current.next = current.next.next;
69 }
70 }
71}
In this JavaScript solution, a straightforward Node class with value and next pointer is used. The MyLinkedList class provides methods to modify nodes using head manipulations and traversals, making list operations concise.
This approach designs a doubly linked list, allowing traversal both forwards and backwards. Each node maintains a reference to both the next and previous node, facilitating operations such as adding or removing nodes from either end more efficiently.
Time Complexity:
- get
: O(n)
- addAtHead
: O(1)
- addAtTail
: O(n)
- addAtIndex
: O(n)
- deleteAtIndex
: O(n)
Space Complexity: O(n), where n is the number of nodes in the list.
1
This Java implementation of a doubly linked list leverages node classes with additional prev
pointers to streamline navigation and modifications, making it more efficient for certain multi-directional operations.