The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
A singly linked list is the simplest type of linked list in which evey node contains some data and a pointer to the next node of the same data type. Simply, a node contains a data and the address of next node of same data type. A singly linked list allows traversal of data only in one way. i.e) only forward direction.
struct node { int data; struct node *next; };
Here is the program to demonstrate, how to create and use singly linked list.
#include <stdio.h> #include <malloc.h> struct node{ int data; struct node *next; }; struct node *start = NULL; struct node *create_linkedlist(struct node *); struct node *display(struct node *); int main(){ int choice; do{ printf("\n1. Create a list"); printf("\n2. Display the list"); printf("\n3. Exit the list"); printf("\n\nEnter your choice : "); scanf("%d",&choice); switch(choice){ case 1: start = create_linkedlist(start); printf("\n Linked List Created Successfully"); break; case 2: start = display(start); break; } }while(choice != 3); return 0; } struct node *create_linkedlist(struct node *start) { struct node *new_node, *ptr; int num; printf("\n Enter -1 to end"); printf("\n Enter the data : "); scanf("%d",&num); while(num != -1){ new_node = (struct node*)malloc(sizeof(struct node)); new_node -> data = num; if(start == NULL) { new_node -> next = NULL; start = new_node; } else{ ptr = start; while(ptr -> next != NULL) ptr = ptr -> next; ptr -> next = new_node; new_node -> next = NULL; } printf("\n Enter the data : "); scanf("%d",&num); } return start; } struct node *display(struct node *start){ struct node *ptr; ptr = start; while(ptr != NULL) { printf("\t %d", ptr -> data); ptr = ptr -> next; } return 0; }
1. Create a list 2. Display the list 3. Exit the list Enter your choice : 1 Enter -1 to end Enter the data : 5 Enter the data : 1 Enter the data : 2 Enter the data : -1 Linked List Created Successfully 1. Create a list 2. Display the list 3. Exit the list Enter your choice : 2 5 1 2 1. Create a list 2. Display the list 3. Exit the list Enter your choice : 3
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019