I am attempting to write my own template queue class to learn how to use templates. I see that this type of question is asked often, and I have read many of the responses but I still do not see what I am doing wrong.
template <class type>
struct Node{
type data;
Node *next;
};
template <class type>
class LinkedListQueue{
public:
LinkedListQueue();
void push(type new_data);
void pop();
type front();
void print();
private:
Node<type> *head;
Node<type> *tail;
};
template <class type>
LinkedListQueue<type>::LinkedListQueue(){
this->head = NULL;
this->tail = NULL;
}
template <class type>
void LinkedListQueue<type>::push(type new_data){
Node<type> *newNode;
newNode->data = new_data;
newNode->next = NULL;
if(this->head == NULL){
this->head = newNode;
this->tail = newNode;
}else{
this->tail->next = newNode;
this->tail = newNode;
}
}
template <class type>
void LinkedListQueue<type>::pop(){
if(this->head != NULL){
this->head = this->head->next;
if(this->head == NULL){
this->tail == NULL;
}
}else{
cout << "Queue is Empty" << endl;
}
}
template <class type>
type LinkedListQueue<type>::front(){
return(this->head->data);
}
int main() {
LinkedListQueue<int> newQueue;
newQueue.push(5);
newQueue.push(4);
cout << newQueue.front() << endl;
newQueue.pop();
cout << newQueue.front() << endl;
}
I am having trouble determining where the problem is. If I comment off the pop and last front call, the first front() call outputs correctly. However, uncommenting pop and front breaks everything. When I try to debug pop() it seems like there is only one Node in the list.
Any help would be greatly appreciated.
You’re not allocating your new node. just storing the data.
One way or another, you’re always pushing a new element in, so allocate it, set it up, then figure out where it goes. Also, create a constructor for your node that takes a const-ref of the data, and sets the next to NULL. This makes your code significantly more straight-forward (and actually more efficient):
With the Node template becoming:
Finally, your
pop()isn’t deleting the node, just mucking with the pointers. you may want to address that as well.