fork download
  1. // our task is to create a vector now
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. class Node {
  6. public:
  7. int value;
  8. Node* next;
  9. Node* prev;
  10. Node() {
  11. value = 0;
  12. next = NULL;
  13. prev = NULL;
  14. }
  15. Node(int value) {
  16. this->value = value;
  17. next = NULL;
  18. prev = NULL;
  19. }
  20. void setNext(Node* next) {
  21. this->next = next;
  22. }
  23. void setPrev(Node* prev) {
  24. this->prev = prev;
  25. }
  26. void setValue(int value) {
  27. this->value = value;
  28. }
  29. };
  30.  
  31. class Vector {
  32. public:
  33. Node* head;
  34. Node* tail;
  35. Vector() {
  36. head = new Node();
  37. tail = head;
  38. }
  39.  
  40. // tail = 'banani'
  41. // newNode = 'shewrapara'
  42. // tail-next = newnode = 'shewrapara'
  43. // newPrev->prev = tail = 'banani'
  44. // tail = 'shewrapara'
  45. void push_back(int value) {
  46. Node* newNode = new Node(value);
  47. tail->next = newNode;
  48. newNode->prev = tail;
  49. tail = newNode;
  50. }
  51. void pop_back() {
  52. if(tail == head) {
  53. cerr << "vector is empty, so your can't pop" << endl;
  54. return; // vector is empty so nothing to pop
  55. }
  56. tail = tail->prev;
  57. tail->next = NULL;
  58. }
  59. int back() {
  60. if(tail == head) {
  61. cerr << "vector is empty, so your can't pop" << endl;
  62. return -1;
  63. }
  64. return tail->value;
  65. }
  66. int front() {
  67. if(head->next == NULL) {
  68. cerr << "vector is empty, so your can't pop" << endl;
  69. return -1;
  70. }
  71. return head->next->value;
  72. }
  73.  
  74. void push_front(int value)
  75. {
  76. Node* newNode = new Node(value);
  77. newNode->next = head->next;
  78. newNode->prev = head;
  79. head->next = newNode;
  80. }
  81.  
  82. void pop_front()
  83. {
  84. if(head->next == NULL){
  85. cerr << "Vector is empty so you cannot pop front" << endl;
  86. return;
  87. }
  88. Node* del_node = head->next;
  89. head->next = del_node->next;
  90. if(del_node->next != NULL)
  91. {
  92. del_node->next->prev = head;
  93. }
  94. }
  95. };
  96.  
  97. int main() {
  98. Vector v;
  99. v.push_back(5);
  100. cout << v.front() << endl;
  101. v.pop_front();
  102. cout << v.front() << endl;
  103. v.pop_front();
  104. v.push_front(10101);
  105. cout << v.front() << endl;
  106. }
Success #stdin #stdout #stderr 0.01s 5292KB
stdin
Standard input is empty
stdout
5
-1
10101
stderr
vector is empty, so your can't pop
Vector is empty so you cannot pop front