Skip to content

Introduction to Linked Lists

Course: Linked List - chapter 1

Linked List is another linear data structure. It is similar to arrays but the major difference is, in a linked list, the elements are not next to each other in memory like that in arrays. In array, the elements occupy a continuous block of memory, whereas in linked list, the elements do not occupy consecutive blocks. As a result, we cannot use indices in linked list. Each element (we call it a node of a linked list) holds the address (or reference) to the next node.

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSohnX0uFxyLouJXpTvdirTgcl9Msl1JYPb_XV4ZbcDQ&s

Each element (or node) in a linked list holds at least 2 values:

  1. The data to be stored
  2. Pointer to the next node

2 important nodes of a linked list are:

  1. **Head: **The head is a pointer to the first node of a linked list. We begin our iteration from this node. Generally in every linked list, head node will be given.
  2. **Tail: **The tail is a pointer to the last node of a linked list. This is optional.

First let’s define a class that describes a Node. Let’s say each element holds an integer value.

class Node {
int data;
Node *next;
public:
Node() {
this.data = 0;
this.next = NULL;
}
Node(int v, Node *next) {
this.data = v;
this.next = next;
}
};

Now let’s write a method that adds a node at the end of the linked list.

Node* addAtEnd(Node *head, Node newElement) {
if (head == NULL) {
// If head is NULL. It means the linked list is empty
head = &newElement;
} else {
Node *curr = head;
while(curr->next != NULL) {
//next is NULL only for the last node
curr = curr->next;
}
curr->next = &newElement;
}
return head;
}

To iterate in a linked list, we can start at the head node and go as long as we don’t reach the last node. The last node is identified using node.next == NULL

Node *curr = head;
while (curr->next != NULL) {
// Do something with curr node
curr = curr->next;
}