Doubly Linked List Structure and Node Design in DSA C - Time & Space Complexity
We want to understand how the time to work with a doubly linked list changes as it grows.
Specifically, how fast can we access or change nodes based on the list size?
Analyze the time complexity of the following code snippet.
// Define a node in a doubly linked list
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
This code creates a single node with pointers to the previous and next nodes.
In this snippet, there are no loops or recursion.
- Primary operation: Allocating and initializing one node.
- How many times: Exactly once per call.
Since this creates only one node at a time, the work does not grow with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 node creation |
| 100 | 1 node creation |
| 1000 | 1 node creation |
Pattern observation: The time to create a node stays the same no matter how big the list is.
Time Complexity: O(1)
This means creating a node takes the same amount of time regardless of list size.
[X] Wrong: "Creating a node takes longer as the list grows because it has to connect to all nodes."
[OK] Correct: Creating a node only sets its own pointers; linking it to the list happens separately and usually involves just a few pointer changes.
Understanding node creation time helps you explain how linked lists build up and why some operations are fast or slow.
"What if we added a loop to traverse the list to find the last node before adding the new node? How would the time complexity change?"
