al__nasim

queue

Jul 18th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node{
  5. int element;
  6. struct node* next;
  7. };
  8.  
  9. struct Queue{
  10. struct node* front;
  11. struct node* rear;
  12. };
  13.  
  14. bool isEmpty(Queue* q){
  15. if(q->front==NULL)
  16. return true;
  17. else
  18. return false;
  19. }
  20.  
  21. void enqueue(int x, Queue* q){
  22. struct node* t = (struct node*) malloc(sizeof(struct node));
  23. t->element = x;
  24. t->next = NULL;
  25.  
  26. if(isEmpty(q)){
  27. q->front = q->rear = t;
  28. //cout << "Enqueue done" << endl;
  29. }
  30. else{
  31. q->rear->next = t;
  32. q->rear = t;
  33. //cout << "Enqueue done" << endl;
  34. }
  35. }
  36.  
  37. void dequeue(Queue* q){
  38. if(isEmpty(q)){
  39. cout << "Queue is already empty" << endl;
  40. return;
  41. }
  42. else if(q->front == q->rear){
  43. struct node* t = q->front;
  44. q->front = q->rear = NULL;
  45. free(t);
  46. }
  47. else{
  48. struct node* t = q->front;
  49. q->front = q->front->next;
  50. free(t);
  51. }
  52.  
  53. }
  54.  
  55. int peek(Queue *q){
  56. if(isEmpty(q)){
  57. //cout << "Queue is already empty" << endl;
  58. return -9999;
  59. }
  60. return q->front->element;
  61. }
  62.  
  63. void traversal(Queue *q){
  64. struct node* cur = q->front;
  65. while(cur!=NULL){
  66. cout << cur->element << endl;
  67. cur = cur->next;
  68. }
  69. }
  70.  
  71. struct Queue* Q[100];
  72. struct Queue* MQ;
  73.  
  74. int main(){
  75. //freopen("input.txt","r",stdin);
  76. int N;
  77. int s, d, root;
  78.  
  79. cin >> N;
  80. cin >> root;
  81. for(int i=1; i<=N; i++)
  82. Q[i] = (struct Queue*)malloc(sizeof(struct Queue));
  83.  
  84. while(cin>>s>>d){
  85. enqueue(d,Q[s]);
  86. enqueue(s,Q[d]);
  87. }
  88.  
  89. for(int i=1; i<=N; i++){
  90. cout << "Traversing Lists for vertex: " << i << endl;
  91. traversal(Q[i]);
  92. }
  93.  
  94. /*
  95. MQ = (struct Queue*) malloc(sizeof(struct Queue));
  96. cout << "Executing BFS from root vertex " << root << ".... " << endl;
  97. BFS(root);
  98. */
  99.  
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment