The need:
This program shows how one can implement concept of queue in linked lists. I have already told that linked lists are needed when we practically don't want a bound on size of data being used in program. So unlike array implementation this program will never show "cannot enqueue" message until your computer is out of memory.
The code:
------------------------------------------------------
------------------------------------------------------
This program shows how one can implement concept of queue in linked lists. I have already told that linked lists are needed when we practically don't want a bound on size of data being used in program. So unlike array implementation this program will never show "cannot enqueue" message until your computer is out of memory.
The code:
------------------------------------------------------
/*
This is a program showing the queue implimentation on linked list
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node1
{
int item;
struct node1 *next;
};
typedef struct node1 node; //defining datatype node
void enqueue(node *);
node* dequeue(void);
node *create_node(void);
void fill_node(node *);
void print_node(node *);
node *front=NULL, *rear=NULL; //global implementation of queue
int main()
{
int i,j;
node *current_node;
printf("Enter 3 items into queue\n");
for(i=0;i<3;i++)
{
current_node=create_node();
fill_node(current_node);
enqueue(current_node);
printf("item %d inserted into queue successfully\n",current_node->item);
}
printf("all items successfully entered into queue\n");
printf("press any key to dequeue and see all values you entered");
fflush(stdin);
getchar();
while(!(rear==NULL&&front==NULL))
{
current_node=dequeue();
print_node(current_node);
}
return 0;
}
void enqueue(node *p) //definition of enqueue function
{
if(rear==NULL&&front==NULL)
{
rear=p;
front=p;
}
else
{
rear->next=p;
rear=p;
}
}
node *dequeue(void) //definition of dequeue function
{
node *temp=NULL;
if(rear==NULL&&front==NULL) //this is the case when queue is empty
{
printf("queue is empty hence can not be dequeued\n");
}
else if(rear==front&&front!=NULL) //this is the case when queue has only one node
{
temp=front;
front=NULL;
rear=NULL;
}
else
{
temp=front;
front=front->next;
}
return temp;
}
node *create_node() //function to create a blank node
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->next=NULL;
return temp;
}
void fill_node(node *p) //function to fill a blank node with values taken from user
{
int i;
printf("Enter an integer\n");
scanf("%d",&i); //this is the value taken from user
p->item=i;
}
void print_node(node *p) //printing the node data
{
printf("%d\n",p->item); //in our case node has only one item
}------------------------------------------------------
No comments:
Post a Comment
feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply