• Source
    1. #include <iostream>
    2. using namespace std;
    3.  
    4. typedef struct node{
    5. node *prev = nullptr;
    6. node *next = nullptr;
    7. int value;
    8. }node;
    9.  
    10. class stack{
    11. public:
    12. stack();
    13.  
    14. stack(int val);
    15.  
    16. void push(int val);
    17.  
    18. void pop();
    19.  
    20. int top();
    21.  
    22. void traverse();
    23.  
    24. private:
    25.  
    26. node* head;
    27.  
    28. node* tail;
    29.  
    30. };
    31.  
    32. stack::stack(){
    33.  
    34. this->head = (node*)calloc(1,sizeof(node));
    35. this->tail = (node*)calloc(1,sizeof(node));
    36. head->next=tail;
    37. head->prev=head;
    38. tail->next=tail;
    39. tail->prev=head;
    40.  
    41. };
    42.  
    43.  
    44. stack::stack(int val){
    45.  
    46. this->head = (node*)calloc(1,sizeof(node));
    47. this->tail = (node*)calloc(1,sizeof(node));
    48. head->next=tail;
    49. head->prev=head;
    50. tail->next=tail;
    51. tail->prev=head;
    52.  
    53. node* temp = (node*)calloc(1,sizeof(node));
    54. temp->value = val;
    55. head->next = temp;
    56. temp->prev = head;
    57. temp->next = tail;
    58. tail->prev = temp;
    59. };
    60.  
    61. void stack::push(int val){
    62. node* temp = (node*)calloc(1,sizeof(node));
    63. temp->value = val;
    64. temp->prev = head;
    65. temp->next = head->next;
    66. head->next->prev = temp;
    67. head->next = temp;
    68. };
    69.  
    70. void stack::pop(){
    71. node *temp = head->next;
    72. temp->prev->next = temp->next;
    73. temp->next->prev = head;
    74. temp->next = temp;
    75. temp->prev = temp;
    76. free(temp);
    77. }
    78.  
    79. int stack::top(){
    80. return this->head->next->value;
    81. };
    82.  
    83. void stack::traverse(){
    84. node *temp = this->head->next;
    85. if(temp==this->tail){
    86. printf("no elements.");
    87. return;
    88. }
    89. while(temp!=this->tail){
    90. printf("%d ",temp->value);
    91. temp=temp->next;
    92. }
    93. printf("\n");
    94. return;
    95. }
    96.  
    97.  
    98. int main() {
    99. stack* test = new stack(3);
    100. stack* test2 = new stack();
    101. test2->push(1);
    102. test->push(4);
    103. test->push(7);
    104. test->push(9);
    105. printf("%d\n",test->top());
    106. test->traverse();
    107. printf("%d\n",test2->top());
    108. test2->traverse();
    109. return 0;
    110. }