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 MyLinkedList {
2 class Node {
3 int val;
4 Node next;
5 Node(int val) { this.val = val; }
6 }
7
8 private Node head;
9
10 public MyLinkedList() {
11 head = null;
12 }
13
14 public int get(int index) {
15 Node current = head;
16 for (int i = 0; current != null && i < index; i++) {
17 current = current.next;
18 }
19 return current == null ? -1 : current.val;
20 }
21
22 public void addAtHead(int val) {
23 Node node = new Node(val);
24 node.next = head;
25 head = node;
26 }
27
28 public void addAtTail(int val) {
29 Node node = new Node(val);
30 if (head == null) {
31 head = node;
32 return;
33 }
34 Node current = head;
35 while (current.next != null) {
36 current = current.next;
37 }
38 current.next = node;
39 }
40
41 public void addAtIndex(int index, int val) {
42 if (index == 0) {
43 addAtHead(val);
44 return;
45 }
46 Node current = head;
47 for (int i = 0; current != null && i < index - 1; i++) {
48 current = current.next;
49 }
50 if (current == null) return;
51 Node node = new Node(val);
52 node.next = current.next;
53 current.next = node;
54 }
55
56 public void deleteAtIndex(int index) {
57 if (index == 0 && head != null) {
58 head = head.next;
59 return;
60 }
61 Node current = head;
62 for (int i = 0; current != null && i < index - 1; i++) {
63 current = current.next;
64 }
65 if (current != null && current.next != null) {
66 current.next = current.next.next;
67 }
68 }
69}
The Java solution creates a simple singly linked list using inner classes for the nodes. The main methods support adding nodes to the head, the tail, and at specific indices while maintaining links consistently.
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
The C implementation of a doubly linked list adds a prev
pointer to each node, enabling two-way node traversal and efficient deletion and insertion operations from both ends.