Queue:
A queue is a linear list of element in which
è Deletion can take place at one end that is Front .
è Insertion take place at one end that is Rear ..
That's why Also known as FILO :-first in last out
That's why Also known as FILO :-first in last out
Algorithm to Insertion in Queue :
Insertion in queue always take place at rear
1:-create a new node (=temp ) and assign data to it
2:-rear->link=temp and temp->link=NULL
3:-rear=rear->link
4:-Exit
Algorithm to Deletion from Queue :
Deletion from queue always take place at front .
1:- create a pointer of type struct node (let temp)
2:-temp=front
3:-front=front->link
4:-free temp
5:-Exit
Queue implementation Using one way link list :
- // Queue implementation in one way link List
- //http://beginer2cs.blogspot.com
- #include<stdio.h>
- #include<malloc.h>
- #include<stdlib.h>
- struct node{ //structure of a single node
- int data;
- struct node *link;
- }*front,*rear;
- typedef struct node node; //typedef
- void add(){
- int d;
- node *temp; //var of type node(i.e struct node)
- printf("\nEnter data to add :");
- scanf("%d",&d);
- // Alocate sapce for new node
- temp=(node *)malloc(sizeof(node));
- if(temp==NULL){
- printf("Overflow condition ?? ");
- }
- temp->data=d; //add data to node
- temp->link=NULL;
- //if queue is empty
- if(front==NULL ){
- front=temp;
- rear=temp;
- }
- else{
- //if Queue is not empty
- rear->link=temp;
- rear=temp;
- }
- }
- void del(){
- //deletion is always from front
- if(front == NULL){
- printf("\nUnderflow condition .. Queue is empty\n");
- }
- else{
- node *temp;
- temp=front; //point to first node
- front=front->link; //now front point 2 second node
- free(temp); //deallocate space of first node
- }
- }
- void display(){
- node *ptr;
- printf("\n");
- if(front==NULL){
- printf("\nQUeue is empty\n");
- }
- else{
- ptr=front;
- while(ptr!=NULL){
- printf(" %d ",ptr->data);
- ptr=ptr->link;
- }
- printf("\n");
- }
- }
- main(){
- int ch;
- front=NULL; //Initiate queue
- rear=NULL;
- while(1){
- printf(" 1: add data \n 2: delete \n 3 : exit \n Enter your choice :");
- scanf("%d",&ch);
- switch(ch){ //select opearation to done on queue
- case 1:
- add();
- display();
- break;
- case 2:
- del();
- display();
- break;
- case 3:
- exit(0);
- break;
- default:
- printf("Wrong Choice !! try again");
- break;
- }
- }
- }
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT