【发布时间】:2020-07-10 15:22:58
【问题描述】:
//This program implements queue using Linked List
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
struct Node* front=NULL;
struct Node* rear=NULL;
void Enqueue(int x){
struct Node* new_node=new Node();
new_node->data=x;
new_node->next=NULL;
if(front==NULL && rear==NULL){
front=rear=new_node;
return;
}
rear->next=new_node;
rear=new_node;
}
void Dequeue(){
struct Node* temp=front;
if(front==rear){
front=rear=NULL;
return;
}
else{
front=front->next;
}
delete temp;
}
void display(){
struct Node* current=front;
while(current!=NULL){
cout<<current->data<<" ";
current=current->next;
}
}
int main(){
cout<<"Enqueuing......"<<endl;
Enqueue(5);
Enqueue(4);
Enqueue(1);
Enqueue(8);
display();
cout<<"\nDequeuing......"<<endl;
Dequeue();
display();
return 0;
}
在 void Dequeue() 中,使用了 delete temp,但我没有在堆内存中分配 Node* temp,但它仍然删除了 temp Node。但是只有在堆中分配了一些东西时才能使用删除。 PS:代码运行良好我只是想知道delete是否可以用于在静态内存分配中删除。
【问题讨论】:
-
Why should I not #include <bits/stdc++.h>?。不要永远
#include <bits/stdc++.h>- 千万不要。这是一个特定于实现的标头,它不供您包含。然后你甚至用using namespace std;跟进它,所以现在你已经拖入了整个标准库,破坏了你的编译时间,严重污染了全局命名空间并使你的程序不可移植,所有这些都在两行代码中。不要那样做 - 永远!
标签: c++ data-structures linked-list heap-memory