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?
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?
Code:
template <typename T>
class TQueue
{
public:
TQueue();
~TQueue();
void Push (const T& t); //push t onto queue
T Pop (); //pop queue and return removed element; error if empty
T& Front (); //return front element of stack; error if empty
const T& Front () const; //const version
size_t Size () const; //return number of elements in queue
int Empty () const; //return 1 if queue is empty, 0 if not empty
void Clear (); //make the queue empty
void Display (std::ostream& os, char ofc) const; //outputs contents through os
private:
class Link
{
Link (const T& t) : element_(t), nextLink_(0) {}
T element_;
Link * nextLink_;
friend class TQueue<T>;
};
Link * firstLink_;
Link * lastLink_;
};
template <typename T>
std::ostream& operator << (std::ostream& os, const TQueue<T>& S)
{
S.Display(os, '\0');
return os;
}
template <typename T>
TQueue<T>::TQueue():firstLink_(0), lastLink_(0){;}
template <typename T>
TQueue<T>::~TQueue()
{
Clear();
}
template <typename T>
void TQueue<T>::Push(const T& t)
{
Link * newLink = new Link (t);
if(firstLink_ == 0)
{
firstLink_ = lastLink_ = newLink;
}
else
{
lastLink_ -> nextLink_ = newLink;
lastLink_ = newLink;
}
}
template <typename T>
T TQueue<T>::Pop()
{
firstLink_ = firstLink_ -> nextLink_;
if (firstLink_ == 0)
firstLink_ = lastLink_;
return firstLink_ -> element_;
delete firstLink_;
}
template <typename T>
T& TQueue<T>::Front()
{
return firstLink_ -> element_;
}
Comment