我们可以删除链表中静态内存中的节点吗

Can we delete a Node in Linked List which is in static memory?

本文关键字:内存 节点 静态 我们 删除 链表      更新时间:2023-10-16
//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。但只有在堆中分配了某些内容时,才能使用delete。PS:代码运行良好,我只想知道delete是否可以用于静态内存分配中的删除。

此代码:

struct Node* temp = front;
// ...
delete temp;

只要front指针指向动态分配的内存。

请注意,此代码段中的struct关键字是多余的。