A linked list is a linear data structure that stores a collection of data elements dynamically.Nodes represent those data elements and links or pointers connect each node.Each node consists of two fields the information sorted in a linked list and a pointer that stores the address of its next node
Representation of a linked list:
start ---> 10| | |20| | |30| |
here 10 and the blank space is a node
10= data
blank space is the pointer
struct node
{
int data;
struct node*next
};
struct node*n;
n=(struct node*)malloc(sizeof(struct node*));
Types of linked list:
1.singly linked list
2. doubly linked list
3. circular linked list
singly linked list:
start--> data|next| ---> data|next--->data|null
doubly linked list:
start--->prev|data|next|<---> prev|data|next|<----->prev|data|next|<---->prev|data|null|---->null
circuler kinked list:
start---->data|next|--->data|next|--->data|next|---->start
operations:
1.traversing
2.insertion
3.deletion
4.searching
Traversing in a linked list
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
int main(){
struct Node *a = NULL;
struct Node *b= NULL;
struct Node *c = NULL;
a = (struct Node*)malloc(sizeof(struct Node));
b = (struct Node*)malloc(sizeof(struct Node));
c = (struct Node*)malloc(sizeof(struct Node));
a->data = 10;
b->data = 20;
c->data =30;
a->next= b;
b->next=c;
c->next=NULL;
while(a!=NULL){
printf("%d ->",a->data);
a=a->next;
}
return 0;
}
inserting in linked list :
#include<stdio.h>
#include<stdlib.h>
void beginsert(int);
struct node
{
int data;
struct node *next;
};
struct node *head;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
beginsert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void beginsert(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted\n");
}
}
0 Comments