nie-ii-year

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

list.cpp (1933B)


      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* updateHead(node* h){
     12     this->next = h;
     13     return this;
     14   };
     15   node* updateNode(){
     16     return this->next;
     17   };
     18   int getValue(){
     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 list{
     30   node* head;
     31 public:
     32   list(){head = NULL;};
     33   friend bool isNULL(node*);
     34   void prepend(int x){
     35     node* temp = new node(x);
     36     if(temp == NULL){
     37       std::cout << "Insufficient memory." << '\n';
     38       return;
     39     }
     40     else{
     41       if(isNULL(head))
     42         head = temp;
     43       else
     44         head = temp->updateHead(head);
     45     }
     46   };
     47   void remove(){
     48     if(isNULL(head)){
     49       std::cout << "List is empty." << '\n';
     50       return;
     51     }
     52     else{
     53       node*temp = head;
     54       head = head->updateNode();
     55       std::cout << temp->getValue() << " has been deleted.\n";
     56       delete temp;
     57     }
     58   };
     59   void display(){
     60     node*temp = head;
     61     if(isNULL(temp)){
     62       std::cout << "List is empty." << '\n';
     63       return;
     64     }
     65     else
     66       for(int i = 1; temp != NULL; i++, temp = temp->updateNode())
     67         std::cout << i << ". " << temp->getValue() << '\n';
     68   };
     69 };
     70 
     71 int main(){
     72   list l;
     73   int choice;
     74   std::cout << "1. Enter 2. Delete 3. Print 4. Exit" << '\n';
     75   do{
     76     std::cout << "Your choice> ";
     77     std::cin >> choice;
     78     switch (choice) {
     79       case 1:
     80               std::cout << "Enter element to be prepended: " << '\n';
     81               std::cin >> choice;
     82               l.prepend(choice);
     83               choice = 1;
     84               break;
     85       case 2:
     86               l.remove();
     87               break;
     88       case 3:
     89               l.display();
     90               break;
     91       case 4:
     92               choice = 0;
     93               break;
     94       default: std::cout << "Invalid input, try again." << '\n';
     95     }
     96   }while(choice);
     97   return 0;
     98 }