473,699 Members | 2,531 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Making a Queue

54 New Member
I have to make a queue utilizing a linked list for an assignment. When I Push() an item to the queue, and try to Pop() or return the Front() element, it says the queue is empty. When I Push() another element to the queue and Pop() or return the Front(), the first entered element is returned.
Say I enter 4 element and then Pop(), it pops elements 2, 3, 4 and then says the queue is empty.
Somewhere along the line I am missing a key line to ensure the queue can see only 1 element.
Also, how would I determine the Size() of the queue based on what I have to go by?

Expand|Select|Wrap|Line Numbers
  1. template <typename T>
  2. class TQueue
  3. {
  4. public:
  5.   TQueue();
  6.   ~TQueue();
  7.   void     Push     (const T& t); //push t onto queue
  8.   T        Pop      ();           //pop queue and return removed element; error if empty
  9.   T&       Front    ();           //return front element of stack; error if empty
  10.   const T& Front    () const;     //const version
  11.   size_t   Size     () const;     //return number of elements in queue
  12.   int      Empty    () const;     //return 1 if queue is empty, 0 if not empty
  13.   void     Clear    ();           //make the queue empty
  14.   void     Display  (std::ostream& os, char ofc) const; //outputs contents through os
  15. private:
  16.   class Link
  17.   {
  18.     Link (const T& t) : element_(t), nextLink_(0) {}
  19.     T     element_;
  20.     Link * nextLink_;
  21.     friend class TQueue<T>;
  22.   };
  23.   Link * firstLink_;
  24.   Link * lastLink_;
  25. };
  26.  
  27. template <typename T>
  28. std::ostream& operator << (std::ostream& os, const TQueue<T>& S)
  29. {
  30.   S.Display(os, '\0');
  31.   return os;
  32. }
  33.  
  34. template <typename T>
  35. TQueue<T>::TQueue():firstLink_(0), lastLink_(0){;}
  36.  
  37. template <typename T>
  38. TQueue<T>::~TQueue()
  39. {
  40.   Clear();
  41. }
  42.  
  43. template <typename T>
  44. void TQueue<T>::Push(const T& t)
  45. {
  46.   Link * newLink = new Link (t);
  47.   if(firstLink_ == 0)
  48.   {
  49.     firstLink_ = lastLink_ = newLink;
  50.   }
  51.   else
  52.   {
  53.     lastLink_ -> nextLink_ = newLink;
  54.     lastLink_ = newLink;
  55.   }
  56. }
  57.  
  58. template <typename T>
  59. T TQueue<T>::Pop()
  60. {
  61.   firstLink_ = firstLink_ -> nextLink_;
  62.   if (firstLink_ == 0)
  63.     firstLink_ = lastLink_;
  64.   return firstLink_ -> element_;
  65.   delete firstLink_;
  66. }
  67.  
  68. template <typename T>
  69. T& TQueue<T>::Front()
  70. {
  71.   return firstLink_ -> element_; 
  72. }
  73.  
Jan 2 '10 #1
5 2805
Banfa
9,065 Recognized Expert Moderator Expert
Your description of the problem must be wrong because Front has no way of "saying the queue is empty" as you have stated.

However your pop function is full of errors, very nearly one per line.

Line 61, the code immediately replaces the element that needs to be returned with the next element of the list. Following this line firstLink_ is not valid for the rest of the function to use.

Line 62 is fine

Line 63, a logic error if firstLink_ is 0 then the list is empty but instead of clearing the value of lastLink_ to the empty value (0) you copy lastLink_ to firstLink_ ensuring that they both point to deallocated memory (or would if your code properly de-allocated memory).

Line 64, the code returns before the function has correctly perform all its required operations, also it uses firstLink_ which no longer points to the correct element to return.

Line 65, this line is never executed so you never deallocate any memory and your queue leaks memory like a sieve.
Jan 2 '10 #2
randysimes
54 New Member
I should have explained a little better; I have a .cpp file which has a menu to do all of the functions of the queue. In Pop() & Front(), I first check if the queue is Empty() and if so, display "Queue is empty"

I am away from my computer at the moment so I will look at your suggestions later.
Thanks Banfa
Jan 2 '10 #3
Banfa
9,065 Recognized Expert Moderator Expert
Well then there may be an error in your implementation of Empty() but that is hard to tell as you never posted the implementation of that method.
Jan 3 '10 #4
randysimes
54 New Member
There was an error in Empty that was corrected last night after I made changes to Pop. I realized that Empty was wrong when I couldn't Pop the first value because it said it was empty.
I am still having difficulty trying to display all the elements of the queue. I have
Expand|Select|Wrap|Line Numbers
  1. std::cout << firstLink_ -> element_;
  2. do
  3. {
  4. std::cout << firstLink_ -> nextlink_;
  5. }
  6. while (firstLink_ -> nextLink_ != 0);
  7.  
It outputs the first element fine, then outputs garbage in an endless loop
Jan 3 '10 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
Where in this loop are you changing firstLink to nextLink to advance in the list?

Also, if firstLink is zero, your loop will crash. The -> requires a non-null LVAL.
Jan 3 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

9
2778
by: phil | last post by:
And sorry I got ticked, frustrating week >And I could help more, being fairly experienced with >threading issues and race conditions and such, but >as I tried to indicate in the first place, you've >provided next to no useful (IMHO) information to >let anyone help you more than this This is about 5% of the code. Uses no locks.
2
1950
by: lucifer | last post by:
hi i am making an http server it has following functions main() { if option is "-?", output the hints and stop check the directory supplied is sensible and not a security risk become a daemon process ignore child programs (to avoid zombies when child processes stop)
3
5148
by: Kceiw | last post by:
Dear all, When I use #include "queue.h", I can't link it. The error message follows: Linking... G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x136): In function `main': G:\Projects\Datastructure\Queue\main.cpp:16: undefined reference to `Queue<char>::Queue()' G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x394): In function `Z10do_commandcR5QueueIcE':
4
4596
by: rzimerman | last post by:
I'm hoping to write a program that will read any number of urls from stdin (1 per line), download them, and process them. So far my script (below) works well for small numbers of urls. However, it does not scale to more than 200 urls or so, because it issues HTTP requests for all of the urls simultaneously, and terminates after 25 seconds. Ideally, I'd like this script to download at most 50 pages in parallel, and to time out if and only...
2
2958
by: lavender | last post by:
When define a maxQueue is 10, means it able to store 10 items in circular queue,but when I key in the 10 items, it show "Queue Full" in items number 10. Where is the wrong in my code? Why it cannot store up to 10 items? Output from my code: Enter you choice: 1 Enter ID document to print : 21 Enter you choice: 1 Enter ID document to print : 22
3
2034
by: jrpfinch | last post by:
I have a script which is based on the following code. Unfortunately, it only works on Python 2.3 and not 2.5 because there is no esema or fsema attribute in the 2.5 Queue. I am hunting through the Queue.py code now to try to figure out how to make it work in 2.5, but as I am a beginner, I am having difficulty and would appreciate your help. Many thanks Jon
4
4597
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the length of my queue. I started getting compilation errors when I included a length function. <code> template<class ItemType> void Queue<ItemType>::MakeEmpty() {
2
2929
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
2736
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for bad_alloc #include <iostream> //typedef std::queue<QueueItemTypeQueue; using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
9038
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8887
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6536
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3060
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2351
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2012
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.