Advertisement
Guest User

Untitled

a guest
Jul 7th, 2015
187
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) {}
  34.  
  35. Stack::~Stack() {
  36.   Node* cursor = head;
  37.   Node* next;
  38.  
  39.   while (cursor != NULL)
  40.   {
  41.     next = cursor->next;
  42.     delete cursor;
  43.     cursor = NULL;
  44.     cursor = next;
  45.   }
  46. }
  47.  
  48. void Stack::add(char value) {
  49.   if (size == 0) {
  50.     head = new Node;
  51.     head->data = value;
  52.     head->next = NULL;
  53.   } else {
  54.     Node* ptr = new Node;
  55.     ptr->data = value;
  56.     ptr->next = head;
  57.     head = ptr;
  58.   }
  59.   ++size;
  60. }
  61.  
  62. void Stack::output()
  63. {
  64.   Node* cursor = head;
  65.   while (cursor && cursor->next) {
  66.     cout << cursor->data << endl;
  67.     cursor = cursor->next;
  68.   }
  69.   if (cursor) { cout << cursor->data << endl; }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement