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:
- The data to be stored
- Pointer to the next node
2 important nodes of a linked list are:
- **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.
- **Tail: **The tail is a pointer to the last node of a linked list. This is optional.
Creating a linked list
Section titled “Creating a linked list”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;}Iterating in a linked list
Section titled “Iterating in a linked list”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;}