nie-ii-year

lab stuff from undergrad second year.
git clone http://git.hanabi.in/repos/nie-ii-year.git
Log | Files | Refs | LICENSE

stack.cpp (2018B)


      1 #include <iostream>
      2 
      3 class node{
      4   int data;
      5   node* next;
      6 public:
      7   node(int data){
      8     this->next = NULL;
      9     this->data = data;
     10   };
     11   node* prepend(node* h){
     12     this->next = h;
     13     return this;
     14   };
     15   node* oldElementBecomesHead(){
     16     return this->next;
     17   };
     18   int getCurrentValue(){
     19     return this->data;
     20   }
     21 };
     22 
     23 bool isNULL(node*h){
     24   if(h == NULL)
     25     return true;
     26   return false;
     27 }
     28 
     29 class stack {
     30   node* head;
     31 public:
     32   stack(){
     33     head = NULL;
     34   };
     35   friend bool isNULL(node*);
     36   void operator+(int input){
     37     node* temp = new node(input);
     38     if(isNULL(temp)){
     39       std::cout << "Insufficient memory." << std::endl;
     40       return;
     41     }
     42     else {
     43       if(isNULL(head) == true)
     44         head = temp;
     45       else
     46         head = temp->prepend(head);
     47     }
     48   };
     49   void operator-(){
     50     if(isNULL(head))
     51       std::cout << "Stack underflow." << std::endl;
     52     else{
     53       node *temp = head;
     54       head = head->oldElementBecomesHead();
     55       std::cout << temp->getCurrentValue() << " has been popped." << std::endl;
     56       delete temp;
     57     }
     58   };
     59   void operator<<(int x){
     60     node* temp = head;
     61     if(isNULL(temp)){
     62       std::cout << "Stack is empty." << std::endl;
     63       return;
     64     }
     65     else{
     66       while (temp != NULL) {
     67         std::cout << temp->getCurrentValue() << " ";
     68         temp = temp->oldElementBecomesHead();
     69       }
     70       std::cout << std::endl;
     71     }
     72   };
     73 };
     74 
     75 int main() {
     76   stack s;
     77   int choice, input;
     78   std::cout << "1. Push 2. Pop 3. Display 4. Quit\n";
     79   do{
     80     std::cout << "Your choice> " << '\n';
     81     std::cin >> choice;
     82     switch (choice) {
     83       case 1:
     84               std::cout << "Enter an element to be pushed: ";
     85               std::cin >> input;
     86               s + input;
     87               break;
     88       case 2:
     89               -s;
     90               break;
     91       case 3:
     92                s << 0;
     93               break;
     94       case 4:
     95               choice = 0;
     96               break;
     97       default: std::cout << "Invalid choice, try again." << std::endl;
     98     }
     99   }while(choice);
    100   return 0;
    101 }