How to Create a Linked List in C?
Last Updated :
21 Feb, 2024
A linked list is a data structure in which size can be modified dynamically during the runtime. In the linked list, each element is referred to as a node. Each node in the linked list stores data and a pointer to the next node present in the list. In this article, we will learn how to create a linked list in C.
Example
Input:
Elements for Linked list = {10,20,30,40,50}
Output:
Linked List: 10 -> 20 -> 30 -> 40 -> 50 -> NULL
Create a Linked List in C
Linked List in C can be created by defining a structure that represents the nodes i.e. having a data field and next pointer.
- We can then create the instances of this structure and join them using the next pointers.
- We will keep the pointer to the first element as the head of the linked list.
- We can traverse or refer to the linked list using the pointer to the head.
C Program Create a Linked List
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertAtBeginning( struct Node** head, int data)
{
struct Node* newNode
= ( struct Node*) malloc ( sizeof ( struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void insertAtEnd( struct Node** head, int data)
{
struct Node* newNode
= ( struct Node*) malloc ( sizeof ( struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return ;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
void printList( struct Node* head)
{
struct Node* current = head;
while (current != NULL) {
printf ( "%d -> " , current->data);
current = current->next;
}
printf ( "NULL\n" );
}
int main()
{
struct Node* head = NULL;
insertAtBeginning(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtEnd(&head, 50);
printf ( "Linked List: " );
printList(head);
return 0;
}
|
Output
Linked List: 10 -> 20 -> 30 -> 40 -> 50 -> NULL
Time Complexity: O(N) where N is the total number of nodes in the linked list.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...