/*******************************************************
APPLICATION : Queue Implementation of Linked List
CODED BY : Ankit Pokhrel
COMPILED ON : Borland C++ Ver 5.02
DATE : 2010 - June - 29
********************************************************/
#include "iostream.h"
#include "conio.h"
#include "process.h"
struct Queue //Structure to represent Queue
{
int data;
struct Queue *next,*front,*rear,*head; //Pointers to next node,head,front and rear
};
typedef struct Queue node; //Now, node represent Structure Queue
node *New; //Global Variable to represent node
void initialize(node *n)
{
n -> next = n -> head = n -> front = n -> rear = NULL;
}
void create(node *n)
{
New = new node; //Create a new node
New -> data = NULL; //Initialize data
New -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
n -> head = New; //Initialize head
}
void QINSERT(node *n,int ITEM)
{
node *temp = n -> head;
create(n); //Create a Node
New -> data = ITEM; //Insert Item
if(n -> front == NULL && n -> rear == NULL) //If first node
n -> front = n -> rear = New; //front = rear = 1
else
{
while(temp -> next != n -> rear -> next) //move to last node
temp = temp -> next;
temp -> next = New; //Last node points to new node
n -> rear = New; //Now, rear is New node
}
}
node* QDELETE(node *n)
{
if(n -> head == NULL) //If the Queue is Empty
{
cout << "\nQueue Underflow";
exit(0); //Exit from Program
}
node *deleted = n -> front;
if(n -> front == n -> rear) //If only one element
{
n -> head = NULL;
n -> front = n -> rear = NULL;
}
else
n -> front = n -> front -> next; // Move to next node
return deleted; //Return Deleted Node
}
void display(node *n)
{
if(n -> head == NULL) //if no items
{
cout << "Queue is Empty";
return;
}
node *temp = n -> front;
cout << temp -> data << ' '; //Print First Item
while(temp -> next != NULL)
{
temp = temp -> next; //Move to next node
cout << temp -> data << ' '; //Print Next Item
}
}
int main()
{
int i,count = 5;
node *list1 = new node,*list2 = new node,*list3 = new node;
//Initialize all lists to avoid errors
initialize(list1);
initialize(list2);
initialize(list3);
cout << "Elements of First Queue : ";
for(i = 1;i <= count;i++)
QINSERT(list1,5*i); //Push 5 elements on Queue
display(list1); //Display Elements of First List
cout << "\n\nElements of Second Queue : ";
for(i = 1;i <= count;i++)
QINSERT(list2,7*i); //Push 5 elements on Queue
display(list2); //Display Elements of Second List
QINSERT(list3,(QDELETE(list1) -> data + QDELETE(list2) -> data)); //Add Elements of First Node and save to Third List
i = 1; //Starts from 1 because first node is already processed
while(i < count)
{
QINSERT(list3,(QDELETE(list1) -> data + QDELETE(list2) -> data)); //Add Elements
i++;
}
cout << "\n\nElements of Third Queue (After Addition) : ";
display(list3);
getch();
return 0;
}
......................
Labels:
Linked List
No comments:
Post a Comment