0
//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;
}

In void Dequeue(), delete temp is used but I haven't allocated the Node* temp in Heap memory, but still it deletes the temp Node. But delete can only be used when something is allocated in Heap. PS: The code is working fine I just want to know if delete can be used to delete in static memory allocation .

cigien
  • 57,834
  • 11
  • 73
  • 112
  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058). Don't *ever* `#include ` - just don't. It's an implementation specific header, it's *not* there for you to include. And then you even follow it up with `using namespace std;`, so now you've dragged in the entire standard library, ruined your compile times, grossly polluted the global namespace and made your program non-portable, all in two lines of code. Don't do that - *ever*! – Jesper Juhl Jul 10 '20 at 16:03

1 Answers1

0

This code:

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

is perfectly fine, so long as the front pointer is pointing to dynamically allocated memory.

Note that the struct keyword in this snippet is redundant.

cigien
  • 57,834
  • 11
  • 73
  • 112