Skip to content

Instantly share code, notes, and snippets.

@harish-r
Created September 7, 2014 08:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harish-r/4428cf99df4890f21a26 to your computer and use it in GitHub Desktop.
Save harish-r/4428cf99df4890f21a26 to your computer and use it in GitHub Desktop.
Queue - Linked List Implementation in C++
// Queue - Linked List Implementation
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class Queue
{
Node *head;
Node *tail;
Node *prev;
Node *temp;
bool isEmpty()
{
return head == NULL;
}
public:
Queue()
{
head = NULL;
tail = NULL;
}
void enqueue(int x)
{
temp = new Node;
temp->data = x;
temp->next = NULL;
if(isEmpty())
{
head = temp;
tail = temp;
}
else
{
prev = tail;
tail->next = temp;
tail = temp;
}
}
void dequeue()
{
temp = head;
head = head->next;
delete temp;
}
void find(int x)
{
int i;
for(i=1, temp = head;temp->next != NULL && temp->data != x;temp = temp->next, i++);
if(temp->data == x)
{
cout << "Found at position:" << i << endl;
}
else if(temp->next == NULL)
{
cout << "Error: Number Not found..." << endl;
}
}
void display()
{
if(!isEmpty())
{
for(temp = head; temp != NULL; temp=temp->next)
cout << temp->data << " ";
cout << endl;
}
else
{
cout << "Queue is Empty!" << endl;
}
}
};
int main()
{
Queue q;
q.display();
q.enqueue(15);
q.display();
q.enqueue(25);
q.display();
q.enqueue(35);
q.display();
q.enqueue(45);
q.display();
q.find(15);
q.dequeue();
q.display();
q.dequeue();
q.display();
q.dequeue();
q.display();
}
@maxgoren
Copy link

maxgoren commented Aug 9, 2020

This is not a Queue;

  1. queue's disallow access to any element beyond the first, you can only push an item on to a queue, or pop an item off a queue, thus there should not be a find() function.
  2. dequeueing should return the value of the first item on the queue, not delete the whole queue.
  3. what purpose does display() serve? either dequeue or display() should return the value and then remove it from the stack.

What you have here is merely a linked list with odd access specifiers. Good try though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment