fork(1) download
  1. /*Implementation of "queue" with basic operations using LINKED LIST */
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. struct node{
  6. int val;
  7. node *next;
  8. }*head=NULL, *tail=NULL;
  9.  
  10.  
  11. void ENQUE(int key); // ~insertion
  12. int DEQUEUE(); // ~deletion
  13. void TRAVERSE();
  14. bool isEmpty();
  15. // a q implemented using linked list can never be full theoretically
  16. int main(){
  17. int ch,key;
  18. do{
  19. cout<<"1. Insertion\n2. Deletion\n3. Traverse\n4. Exit\n";
  20. cout<<"Enter your choice : ";
  21. cin>>ch;
  22. switch(ch){
  23. case 1 : cout<<"Enter the value to be inserted :";
  24. cin>>key;
  25. ENQUE(key);
  26. TRAVERSE();
  27. break;
  28. case 2 : if(!isEmpty()){
  29. cout<<DEQUEUE()<<" deleted successfully.\n";
  30. TRAVERSE();
  31. }
  32. else
  33. cout<<"Empty Queue !!!\n";
  34. break;
  35. case 3 : TRAVERSE();
  36. break;
  37. case 4 :cout<<"Exiting...";
  38. break;
  39. default: cout<<"Invalid choice. Please try again..";
  40. }
  41. }while(ch!=4);
  42. return 0;
  43. }
  44.  
  45. void ENQUE(int x){
  46. if(tail==NULL){
  47. tail = new node();
  48. tail->val =x;
  49. tail->next=NULL;
  50. head=tail;
  51. }
  52. else{
  53. tail->next = new node();
  54. tail = tail->next;
  55. tail->val =x;
  56. tail->next=NULL;
  57. }
  58. }
  59.  
  60. int DEQUEUE(){
  61. node *temp = head;
  62. int item =head->val;
  63.  
  64. head = head->next;
  65. delete(temp);
  66.  
  67. if(head==NULL)
  68. tail=NULL;
  69. return item;
  70. }
  71.  
  72. void TRAVERSE(){
  73. if(!isEmpty()){
  74. node *ptr = head;
  75. cout<<"\nhead";
  76. while(ptr){
  77.  
  78. cout<<" -> "<<ptr->val;
  79. ptr=ptr->next;
  80. }
  81. cout<<" <- tail\n";
  82. cout<<endl;
  83. }
  84. else
  85. cout<<"Empty Queue !!!\n";
  86. }
  87.  
  88. bool isEmpty(){
  89. if(tail==NULL && head==NULL)
  90. return true;
  91. else
  92. return false;
  93. }
  94.  
Success #stdin #stdout 0s 2992KB
stdin
1
1
1
2
1
3
2
2
4
stdout
1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : Enter the value to be inserted :
head -> 1 <- tail

1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : Enter the value to be inserted :
head -> 1 -> 2 <- tail

1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : Enter the value to be inserted :
head -> 1 -> 2 -> 3 <- tail

1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : 1 deleted successfully.

head -> 2 -> 3 <- tail

1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : 2 deleted successfully.

head -> 3 <- tail

1. Insertion
2. Deletion
3. Traverse
4. Exit
Enter your choice : Exiting...