demonstrate the implementation of singly linked list.
Description:
In this example you will see how to create a node and insert data record in singly link list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int num)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = num;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link != NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = num;
temp-> link = NULL;
}
return (p);
}
void printlist ( struct node *p )
{
printf("The data values of your list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}
void main()
{
int n;
int x;
struct node *start = NULL ;
printf("Enter number of nodes you want to create \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter data values for each node\n");
scanf("%d",&x);
start = insert ( start , x );
}
printf("The created single link list is\n");
printlist ( start );
}
Output:
Previous - Overview of Linked List
Next - Doubly Linked List
Data Structure Tutorial
1. Introduction to Data Structures
2. Pointer in C
3. Pointer and Structure in C
4. Linear and Non-Linear Data Structure in C
5. Array Implementation in C
6. Sum of array element in C
7. Addition of two arrays element in C
8. Inverse of an array in C
9. Merge of two arrays in C
10.Overview of Linked List
11.Singly Linked List
12.Doubly Linked List
13.Circular Linked List
14.Count number of nodes
15.Split a list into two equal size list
16.Merge two list into a single list
17.Stack
18.Push and Pop operation of stack.
19.Push and Pop operation of stack using linked list.
20.Queue implementation using array.
21.Queue implementation using linked list.
22.Circular queue implementation using array.
23.Tree data structure
24.Representing Graph using adjacency list & perform DFS & BFS
0 comments:
Speak up your mind
Tell us what you're thinking... !