【问题标题】:Can we delete a Node in Linked List which is in static memory?我们可以删除静态内存中的链表中的节点吗?
【发布时间】: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 &lt;bits/stdc++.h&gt; - 千万不要。这是一个特定于实现的标头,它供您包含。然后你甚至用using namespace std; 跟进它,所以现在你已经拖入了整个标准库,破坏了你的编译时间,严重污染了全局命名空间并使你的程序不可移植,所有这些都在两行代码中。不要那样做 - 永远

标签: c++ data-structures linked-list heap-memory


【解决方案1】:

这段代码:

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

完全没问题,只要front 指针指向动态分配的内存。

请注意,此 sn-p 中的 struct 关键字是多余的。

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 1970-01-01
    • 2021-02-08
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多