Reputation: 25
I'm implementing my own version of a queue for practice, but wondering if I'm correctly deleting elements correctly, in the "pop()" function.
I'm new to C++ and I'm unsure if I'm just deleting a pointer to the Node I'm trying to delete, instead of the actual node itself.
#include <iostream>
template <typename T>
class Queue {
struct Node {
Node* next;
Node* previous;
T data;
Node(T value){
next = nullptr;
previous = nullptr;
data = value;
}
};
Node* front;
Node* back;
public:
Queue(){
front = nullptr;
back = nullptr;
}
void push_back(T data){
Node* n = new Node(data);
if(front == nullptr){
front = n;
back = n;
} else {
back->next = n;
back = n;
}
}
void print(){
Node* cursor = front;
while(cursor != nullptr){
std::cout << cursor->data << '\n';
cursor = cursor->next;
}
}
T pop(){
Node* temp = front;
T element = temp->data;
front = front->next;
delete temp; // Is this deleting the pointer or the Node it points to?
return element;
}
};
int main(){
Queue<int> q;
q.push_back(1);
q.push_back(2);
q.push_back(3);
q.print();
int element = q.pop();
q.print();
}
Upvotes: 1
Views: 90
Reputation: 31467
delete
deletes the object pointed to by the pointer passed to it.
Upvotes: 6