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.
1#include <iostream>
2
3class MyLinkedList {
4private:
5 struct Node {
6 int val;
7 Node* next;
8 Node(int _val) : val(_val), next(nullptr) {}
9 };
10 Node* head;
11
12public:
13 MyLinkedList() : head(nullptr) {}
14
15 int get(int index) {
16 Node* current = head;
17 for (int i = 0; current && i < index; ++i) {
18 current = current->next;
19 }
20 return current ? current->val : -1;
21 }
22
23 void addAtHead(int val) {
24 Node* node = new Node(val);
25 node->next = head;
26 head = node;
27 }
28
29 void addAtTail(int val) {
30 Node* node = new Node(val);
31 if (!head) {
32 head = node;
33 } else {
34 Node* current = head;
35 while (current->next) {
36 current = current->next;
37 }
38 current->next = node;
39 }
40 }
41
42 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; current && i < index - 1; ++i) {
49 current = current->next;
50 }
51 if (current) {
52 Node* node = new Node(val);
53 node->next = current->next;
54 current->next = node;
55 }
56 }
57
58 void deleteAtIndex(int index) {
59 if (index == 0 && head) {
60 Node* temp = head;
61 head = head->next;
62 delete temp;
63 return;
64 }
65 Node* current = head;
66 for (int i = 0; current && i < index - 1; ++i) {
67 current = current->next;
68 }
69 if (current && current->next) {
70 Node* temp = current->next;
71 current->next = current->next->next;
72 delete temp;
73 }
74 }
75};
This code defines a singly linked list in C++. Nodes are represented by a nested struct with a value and a pointer to the next node. Operations are encapsulated within the MyLinkedList class, manipulating the head pointer directly or through traversals.
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.