Create a Class named List which should contain private membe

Create a Class named List; which should contain private members which can be a node and public functions which are addatfront, addatend, deleteatfront and displayreverse (They are nothing but functions of a linked list which we went through in class).

Solution

#include <iostream>

using namespace std;

//class to represent a node of linked list

class Node {

public:

   int key;

   Node *next;

   Node(int key) {

       this->key = key;

       next = NULL;

   }

   Node(int key, Node *next) {

       this->key = key;

       this->next = next;

   }

};

//class to represent a linked list

class List {

private:

   Node *head;

   Node *tail;

   void displayhelper(Node *n) {

       if (n == NULL) {

           cout << endl;

           return;

       }

       displayhelper(n->next);

       cout << n->key << \"--->\";

   }

public:

   List() {

       head = NULL;

       tail = NULL;

   }

   void addatfront(int element) {

       if (head == NULL) {

           head = new Node(element);

           tail = head;

       } else {

           Node *newnode = new Node(element, head);

           head = newnode;

       }

   }

   void addatend(int element) {

       if (head == NULL) {

           head = new Node(element);

           tail = head;

       } else {

           tail->next = new Node(element);

           tail = tail->next;

       }

   }

   void displayreverse() {

       displayhelper(head);

   }

};

int main() {

   List obj;

   obj.addatfront(3);

   obj.addatfront(2);

   obj.addatfront(1);

   //reverse - list should be 3--->2--->1--->

   obj.displayreverse();

   obj.addatend(4);

   obj.addatend(5);

   obj.addatend(6);

   //reverse - list should be 6--->5--->4--->3--->2--->1--->

   obj.displayreverse();

   return 0;

}

 Create a Class named List; which should contain private members which can be a node and public functions which are addatfront, addatend, deleteatfront and disp
 Create a Class named List; which should contain private members which can be a node and public functions which are addatfront, addatend, deleteatfront and disp
 Create a Class named List; which should contain private members which can be a node and public functions which are addatfront, addatend, deleteatfront and disp

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site