Dan*_*age 1 c++ dynamic-memory-allocation
我正在实现我自己的队列版本以供练习,但想知道我是否在“pop()”函数中正确删除了元素。
我是 C++ 的新手,我不确定我是否只是删除指向我要删除的节点的指针,而不是实际节点本身。
#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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |