TECH GUIDE BLOG

Tech Guide Programming Tutorial Tips Tricks

Queue C++ Data Structure Code

Posted by Admin On February - 15 - 2009

Another data structures type is queue. Adding data is the same as stack, it’s called enqueue. The different between stack is queue use “first in first out”. The first data will be kicked out first when you dequeue it (getting data from queue). There are 2 pointers we can use in queue. Head is pointer that point the first data and tail to point the last data. This picture below may help you to understand.

linear_queue

Linear Queue

There are 2 types of queue, linear and circular. A circular queue has a shape like donut, so we can say the queue is connected. The different is at head position, a linear queue has a static head position, and a circular has a dynamic head position every time you do dequeue.

Circular Queue

Circular Queue

This time, I will only tell you how to make a linear queue class in header :D, it looks like stack application at previous post, so it’s unnecessary to write the main code.

//============== start of code ==============//
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define MAX 255

class lqueue
{
private:
	int data[MAX];
	int tail; // linear queue has a static head, assume head = 0
public:
	lqueue()
	{
		tail = 0;
	}
	void enqueue(int value)
	{
		if (!full())
		{
			data[tail] = value;
			tail++;
		}
	}
	int dequeue()
	{
		if (!empty())
		{
			int temp;
			temp = data[head];
			for (int i = 0; i < tail; i++)
			{
				data[i] = data[i+1];
			}
			tail--;
			return temp;
		}
	}
	bool full()
	{
		if (tail == MAX)
			return 1;
		else
			return 0;
	}
	bool empty()
	{
		if (tail == 0)
			return 1;
		else
			return 0;
	}
	void view()
	{
		for (int i = 0; i < tail; i++)
			printf("%d ",data[i]);
		getch();
	}
};
//=============== end of code ===============//

It’s done. I think it should work fine :))

Popularity: 24% [?]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • MySpace
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Twitter

4 Responses to “Queue C++ Data Structure Code”

  1. adit says:

    yeah..that source code work fine.. can i request for merge sort source?.. :)

  2. Admin says:

    We will think about it, just wait another post, okay! Thank you!

  3. any says:

    i have run this code. why it error said “head” undeclared

  4. Admin says:

    ehmm…. are you sure you put the code in header file? because this code is mainly a header, this code is not fro a main/ cpp file

Leave a Reply