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.
1public class MyLinkedList {
2
3 private class Node {
4 public int val;
5 public Node next;
6 public Node(int _val) { val = _val; }
7 }
8
9 private Node head;
10
11 public MyLinkedList() {
12 head = null;
13 }
14
15 public int Get(int index) {
16 Node current = head;
17 for (int i = 0; i < index && current != null; i++) {
18 current = current.next;
19 }
20 return current == null ? -1 : current.val;
21 }
22
23 public void AddAtHead(int val) {
24 Node node = new Node(val);
25 node.next = head;
26 head = node;
27 }
28
29 public void AddAtTail(int val) {
30 Node node = new Node(val);
31 if (head == null) {
32 head = node;
33 } else {
34 Node current = head;
35 while (current.next != null) {
36 current = current.next;
37 }
38 current.next = node;
39 }
40 }
41
42 public void AddAtIndex(int index, int val) {
43 if (index == 0) {
44 AddAtHead(val);
45 return;
46 }
47 Node current = head;
48 for (int i = 0; i < index - 1 && current != null; i++) {
49 current = current.next;
50 }
51 if (current != null) {
52 Node node = new Node(val);
53 node.next = current.next;
54 current.next = node;
55 }
56 }
57
58 public void DeleteAtIndex(int index) {
59 if (index == 0 && head != null) {
60 head = head.next;
61 return;
62 }
63 Node current = head;
64 for (int i = 0; i < index - 1 && current != null; i++) {
65 current = current.next;
66 }
67 if (current != null && current.next != null) {
68 current.next = current.next.next;
69 }
70 }
71}
This C# implementation uses a nested class to define a Node, and supports various linked list methods by iterating over the nodes starting from the head. It handles nodes creation and insertion/manipulations effectively for singly linked lists.
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 JavaScript solution modifies each node to hold previous pointers as well, ensuring operations such as insertion and deletion take advantage of bi-directional traversal to improve efficiency.