Singly Linked List
A singly linked list is a data structure in which each node contains a value and a reference to the next node in the list. It is a type of linear data structure where each node points only to the next node in the list and does not have a reference to the previous node. The first node in the list is known as the head of the list and the last node in the list has a NULL
value in its reference, indicating the end of the list.
Here’s an example implementation of a singly linked list in C:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head = NULL;
void insertAtBegin(int data){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = head;
head = temp;
}
void printList(){
struct Node* temp = head;
while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
insertAtBegin(1);
insertAtBegin(2);
insertAtBegin(3);
printList();
return 0;
}
In this example, we define a structure Node
with two fields: data
and next
. The head
variable represents the head of the linked list and is initially set to NULL
, indicating an empty list. The insertAtBegin
function creates a new node, sets its data to the given value, and sets the next
reference to the current head of the list. The printList
function iterates through the list and prints the values of each node.