What is a Linked List?
A linked list is a linear data structure where each element (called a node) contains two parts:
- Data: The value stored in the node.
- Pointer (next): A reference to the next node in the list.
Unlike arrays, linked lists do not require contiguous memory locations. They allow dynamic memory allocation and efficient insertion/deletion operations.
Algorithm to Create and Traverse a Linked List
Let’s break down the process into simple steps.
Step-by-Step Algorithm
1. Creation of Linked List
- Start
- Define a node structure with two fields: data and pointer to the next node.
- Create a function to insert a new node at the end:
- Allocate memory for the new node.
- Assign the input data to the node.
- Set the
next
pointer of the node toNULL
. - If the list is empty, make the new node the head.
- Otherwise, traverse to the last node and update its
next
pointer to point to the new node.
- Repeat the insertion as needed.
2. Traversal of Linked List
- Start from the head node.
- While the current node is not
NULL
:- Print the data of the current node.
- Move to the next node.
- End
C Program to Create and Traverse a Linked List
Here is a simple and complete C program:
#include <stdio.h>
#include <stdlib.h>
// Define the structure of a node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end
void insertAtEnd(struct Node** head, int value) {
struct Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to traverse and print the linked list
void traverseList(struct Node* head) {
struct Node* temp = head;
printf("Linked List: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main function
int main() {
struct Node* head = NULL;
// Insert elements into the linked list
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
// Traverse and display the linked list
traverseList(head);
return 0;
}
Output
Linked List: 10 -> 20 -> 30 -> NULL
Explanation
struct Node
: Defines the structure of a single node.createNode()
: Dynamically allocates memory and initializes a new node.insertAtEnd()
: Adds a new node at the end of the list.traverseList()
: Starts from the head and prints each node’s value until the end.
What did you think?