List as an Abstract Data Type
List as an Abstract Data Type
struct Nodepublic:int data;Node* next;class Listpublic:List();constructorList(const list&listl);/copy constructor~List();destructor//boolean functionbool empty()const;// access functionsint headElement() const;//add to the headvoid addHead(int newdata);// delete the headvoid delHead();int length()const;//utiiityfunction// outputvoid print()const;private:Node* head;
struct Node{ public: int data; Node* next; }; class List { public: List(); // constructor List(const list& list1); // copy constructor ~List(); // destructor bool empty() const; // boolean function int headElement() const; // access functions void addHead(int newdata); // add to the head void delHead(); // delete the head int length() const; // utility function void print() const; // output private: Node* head; };
How to use itint i(0);void main()List Liiiconstructor called automatically here for LIntj(10);L.printO:1L.addHead(30);Int k(i);(30)L.print(;L.addHead(13);(1330)L.print();L.addHead(40);(401330L.print();L.addHead(50);L.print();(5040.1330]List N(L);N.print();(50401330)List R;R.print();(if(R.empty())cout<<"ListRempty"<<endl;L.delHead();(401330)L.print();L.delHead();(1330)L.print);if(L.empty())cout << "List L empty" <<endl;else(cout<< "List Lcontains "<< L.length()<<" nodes"<<endl;cout <<"Head element of list L is: "<< L.headElement() << endl;/l destructor called automatically here for L
void main(){ List L; // constructor called automatically here for L L.print(); { } L.addHead(30); L.print(); { 30 } L.addHead(13); L.print(); { 13 30 } L.addHead(40); L.print(); { 40 13 30 } L.addHead(50); L.print(); { 50 40 13 30 } List N(L); N.print(); { 50 40 13 30 } List R; R.print(); { } if(R.empty()) cout << "List R empty" << endl; L.delHead(); L.print(); { 40 13 30 } L.delHead(); L.print(); { 13 30 } if(L.empty()) cout << "List L empty" << endl; else{ cout << "List L contains " << L.length() << " nodes" << endl; cout << "Head element of list L is: " << L.headElement() << endl; } } // destructor called automatically here for L How to use it int i(0); Int j(10); Int k(j);
Motivationlist using static arrayint myArray[1000];int n;We have to decide (to oversize) in advance the size of the array(list)listusing dynamic arrayint* myArray;int n;cin >> n;myArray=new int[n];We allocate an array (list)of any specified size while theprogram isrunninglinked-list (dynamic size)size=??Thelist is dynamic.It can growand shrink to any size
Motivation list using static array int myArray[1000]; int n; We have to decide (to oversize) in advance the size of the array (list) list using dynamic array int* myArray; int n; cin >> n; myArray = new int[n]; We allocate an array (list) of any specified size while the program is running linked-list (dynamic size) size = ?? The list is dynamic. It can grow and shrink to any size
Using a static array
Using a static array