Advertisement
0xCor3

Queue Linked List

May 16th, 2020
1,511
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. using namespace std;
  4. struct node {
  5.    int data;
  6.    struct node *next;
  7. };
  8. struct node* front = NULL;
  9. struct node* rear = NULL;
  10. struct node* temp;
  11. void Insert() {
  12.    int val;
  13.    cout<<"Insert the element in queue : "<<endl;
  14.    cin>>val;
  15.    if (rear == NULL) {
  16.       rear = (struct node *)malloc(sizeof(struct node));
  17.       rear->next = NULL;
  18.       rear->data = val;
  19.       front = rear;
  20.    } else {
  21.       temp=(struct node *)malloc(sizeof(struct node));
  22.       rear->next = temp;
  23.       temp->data = val;
  24.       temp->next = NULL;
  25.       rear = temp;
  26.    }
  27. }
  28. void Delete() {
  29.    temp = front;
  30.    if (front == NULL) {
  31.       cout<<"Underflow"<<endl;
  32.       return;
  33.    }
  34.    else
  35.    if (temp->next != NULL) {
  36.       temp = temp->next;
  37.       cout<<"Element deleted from queue is : "<<front->data<<endl;
  38.       free(front);
  39.       front = temp;
  40.    } else {
  41.       cout<<"Element deleted from queue is : "<<front->data<<endl;
  42.       free(front);
  43.       front = NULL;
  44.       rear = NULL;
  45.    }
  46. }
  47. void Display() {
  48.    temp = front;
  49.    if ((front == NULL) && (rear == NULL)) {
  50.       cout<<"Queue is empty"<<endl;
  51.       return;
  52.    }
  53.    cout<<"Queue elements are: ";
  54.    while (temp != NULL) {
  55.       cout<<temp->data<<" ";
  56.       temp = temp->next;
  57.    }
  58.    cout<<endl;
  59. }
  60. int main() {
  61.    int ch;
  62.    cout<<"1) Insert element to queue"<<endl;
  63.    cout<<"2) Delete element from queue"<<endl;
  64.    cout<<"3) Display all the elements of queue"<<endl;
  65.    cout<<"4) Exit"<<endl;
  66. do {
  67.    cout<<"Enter your choice : "<<endl;
  68.    cin>>ch;
  69.    switch (ch) {
  70.       case 1: Insert();
  71.          break;
  72.       case 2: Delete();
  73.          break;
  74.       case 3: Display();
  75.          break;
  76.       case 4: cout<<"Exit"<<endl;
  77.          break;
  78.       default: cout<<"Invalid choice"<<endl;
  79.    }
  80. } while(ch!=4);
  81.    return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement