fork download
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct node
  6. {
  7. int value;
  8. struct node *next;
  9. };
  10. struct node *head = NULL;
  11. struct node *tail = NULL;
  12.  
  13. void insertHead(int val)
  14. {
  15. //create a new node
  16. struct node *newItem;
  17. newItem=(struct node *)malloc(sizeof(struct node));
  18. newItem->value = val;
  19. newItem->next = NULL;
  20.  
  21. if (head == NULL) tail = newItem;
  22. //insert the new node at the head
  23. newItem->next = head;
  24. head = newItem;
  25. }
  26. void insertTail(int val)
  27. {
  28. //create a new node to be inserted
  29. struct node *newItem;
  30. newItem=(struct node *)malloc(sizeof(struct node));
  31. newItem->value = val;
  32. newItem->next = NULL;
  33. if (head == NULL)
  34. {
  35. head = newItem;
  36. tail = newItem;
  37. return;
  38. }
  39.  
  40. newItem->next = NULL;
  41. tail->next = newItem;
  42. tail = newItem;
  43. }
  44. void printList()
  45. {
  46. if (head == NULL) return;
  47. struct node *cur = head;
  48. while (cur != NULL)
  49. {
  50. printf("%d \t", cur->value);
  51. cur = cur->next;
  52. }
  53. }
  54. int deleteHead()
  55. {
  56. struct node *cur;
  57. if (head == NULL) return -1;
  58. cur = head;
  59. head = head->next;
  60.  
  61. if (head == NULL) tail = NULL;
  62.  
  63. int val = cur->value;
  64. free(cur);
  65. return val;
  66. }
  67.  
  68. class QUEUE{
  69. node* front;
  70. node* rear;
  71.  
  72. public:
  73. QUEUE(){
  74. front = NULL;
  75. rear = NULL;
  76. }
  77.  
  78. void push_back(int val){
  79. //create a new node to be inserted
  80. struct node *newItem;
  81. newItem=(struct node *)malloc(sizeof(struct node));
  82. newItem->value = val;
  83. newItem->next = NULL;
  84. if (front == NULL)
  85. {
  86. front = newItem;
  87. rear = newItem;
  88. return;
  89. }
  90.  
  91. newItem->next = NULL;
  92. rear->next = newItem;
  93. rear = newItem;
  94. }
  95.  
  96. int pop(){
  97. struct node *cur;
  98. if (front == NULL) return -1;
  99. cur = front;
  100. front = front->next;
  101.  
  102. if (front == NULL) rear = NULL;
  103.  
  104. int val = cur->value;
  105. free(cur);
  106. return val;
  107. }
  108. };
  109.  
  110.  
  111. int main(){
  112. QUEUE q;
  113. q.push_back(10);
  114. q.push_back(20);
  115. q.push_back(30);
  116.  
  117. cout<<q.pop()<<endl;
  118. cout<<q.pop()<<endl;
  119. cout<<q.pop()<<endl;
  120. cout<<q.pop()<<endl;
  121. }
  122.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
10
20
30
-1