Skip to content

Instantly share code, notes, and snippets.

@mycodeschool
Last active December 2, 2023 11:22
Show Gist options
  • Save mycodeschool/7510222 to your computer and use it in GitHub Desktop.
Save mycodeschool/7510222 to your computer and use it in GitHub Desktop.
Linked List implementation of Queue.
/*Queue - Linked List implementation*/
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Two glboal variables to store address of front and rear nodes.
struct Node* front = NULL;
struct Node* rear = NULL;
// To Enqueue an integer
void Enqueue(int x) {
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data =x;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
// To Dequeue an integer.
void Dequeue() {
struct Node* temp = front;
if(front == NULL) {
printf("Queue is Empty\n");
return;
}
if(front == rear) {
front = rear = NULL;
}
else {
front = front->next;
}
free(temp);
}
int Front() {
if(front == NULL) {
printf("Queue is empty\n");
return;
}
return front->data;
}
void Print() {
struct Node* temp = front;
while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
/* Drive code to test the implementation. */
// Printing elements in Queue after each Enqueue or Dequeue
Enqueue(2); Print();
Enqueue(4); Print();
Enqueue(6); Print();
Dequeue(); Print();
Enqueue(8); Print();
}
@shivam4786
Copy link

If anyone tried with local front and rear variables in main method !

@Chilled-maskman
Copy link

in the Dequeue function when the second if(front==rear) runs we have to free the space of node pointed by front previously i.e first node is the one when front and rear are equal if we modify the pointer front and rear to NULL we are wasting the memory of first node that was created
please reply
ASAP

Copy link

ghost commented Nov 23, 2019

There is a mistake in dequeue method ..you need to do temp = temp->next;
then free(first); first = temp;
You are freeing the second element each time and if free->next is null then it will crash.

i understand your problem , but see , the case that you're mentioning is when we have only one node in the queue , and here we've explicitly considered that case which is when both front and rear are equal . In that we're deleting simply that one node , not performing
any operation involving , and after the deletion of that single node both front and rear would be pointing to NULL .
I hope i've explained it well .

@akshaysingh02
Copy link

Mycodeschool will always be remembered
Best course on youtube no doubt

@Akashlatya
Copy link

same code in java pls provid it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment