Advertisement
Guest User

Untitled

a guest
Jul 7th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6.   char data;
  7.   Node* next;
  8. };
  9.  
  10. class Stack {
  11.   public:
  12.     Node* head;
  13.     int size;
  14.     void add(char value);
  15.     void output();
  16.     Stack();
  17.     ~Stack();
  18. };
  19.  
  20. int main() {
  21.   Stack stack1;
  22.   stack1.add('h');
  23.   stack1.add('e');
  24.   stack1.add('l');
  25.   stack1.add('l');
  26.   stack1.add('o');
  27.   stack1.output();
  28.  
  29.   return 0;
  30. }
  31.  
  32. Stack::Stack()
  33.   :size(0), head(NULL) {}
  34.  
  35. Stack::~Stack() {
  36.   Node* cursor = head;
  37.   while (cursor != NULL) {
  38.     Node* next = cursor->next;
  39.     delete cursor;
  40.     cursor = NULL;
  41.     cursor = next;
  42.   }
  43. }
  44.  
  45. void Stack::add(char value) {
  46.   Node* node = new Node;
  47.   node->data = value;
  48.   node->next = (size == 0) ? NULL : head;
  49.   head = node;
  50.   ++size;
  51. }
  52.  
  53. void Stack::output() {
  54.   Node* cursor = head;
  55.   if (cursor) {
  56.     while (cursor->next) {
  57.       cout << cursor->data << endl;
  58.       cursor = cursor->next;
  59.     }
  60.     cout << cursor->data << endl;
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement