Learn Computer Science programming - C# and C++ Algorithms

 
Queue C++
A Queue is an ordered collection of elements into which new elements may be inserted at one end, called the rear, and from which elements may be removed at the other end, called the front of the Queue
Picture
CODE
queue.zip
File Size: 5045 kb
File Type: zip
Download File

#include <iostream>
using namespace std;


// Queue
struct Element
{
Element* prev;
Element* next;
int d;
};
class Queue
{
private:
Element* pHead;
Element* pTail;
public:
Queue(){pHead=pTail= NULL;};
int Add_From_Head(int d);
void DeleteLast();
int LastElement();
void Display();

};
int Queue::Add_From_Head(int d)
{
cout << endl << "Adding element from Top: " << d;

Element* NewElement = new Element;
NewElement->next = pHead;
NewElement->prev = NULL;

// If pHead is not NULL - Queue has elements, 
// Assign Head-> to current element as well
if (pHead) pHead->prev = NewElement;

NewElement->d = d;
pHead = NewElement;

// If pTail does not exist. Assign pTail = new element
if (!pTail) pTail = NewElement; //First element only

return NewElement->d;
}
void Queue::DeleteLast()
{
Element* Deleted = pTail;
if (pHead != Deleted)
{
pTail = Deleted->prev;
Deleted->prev->next = NULL;
}
else
{
pTail = pHead = NULL;
}

delete Deleted;
}
int Queue::LastElement()
{
return pTail->d;
}


void Queue::Display ()
{
while (pHead->next  != NULL){
cout << endl << pHead->d  ;
pHead = pHead->next;
}
cout << endl << pHead->d  ;
}
void main()
{
Queue Q;
Q.Add_From_Head (1);
Q.Add_From_Head (12);
Q.Add_From_Head (23);
Q.Add_From_Head (232);
Q.Add_From_Head (23243);
Q.Add_From_Head (66);


Q.Display ();
}

SAMPLE OUTPUT
Adding element from Top: 1
Adding element from Top: 12
Adding element from Top: 23
Adding element from Top: 232
Adding element from Top: 23243
Adding element from Top: 66

Current Content:
66
23243
232
23
12
1

Deleting Element: 1
Deleting Element: 12

Current Content:
66
23243
232
23