110 likes | 135 Views
Understand the concepts and implementations of ADTs such as sets, lists, arrays, and linked lists in C++. Learn the operations and design principles behind ADTs for effective programming practices.
E N D
Abstract Data Types • ADT: A set of objects and a set of operations on those objects. • examples: • integers: +, - , *, … • Collection, insert, remove, … • set: union, intersection, complement, size, … • In C++, the set of operations roughly corresponds to the public member functions of a class. CSE 373, Autumn 2001
ADTs continued • Implementation details can be hidden: member functions access private data members and member functions. • Functions outside the ADT can only access the public data members and functions. • difference between software engineering and hacking: finding the balance between functionality, simplicity, flexibility, and performance. ADT CSE 373, Autumn 2001
List ADT • list of size N: A1, A2, A3, …, AN • The position of Ai is i. • A list of size 0 is the empty list. • operations : • printList ( ) • makeEmpty ( ) • insert (x, pos) • remove (x) • findkth (k) … CSE 373, Autumn 2001
Array Implementation • printList makeEmpty insert remove findkth • Problems? CSE 373, Autumn 2001
Linked List Impl. • insert • delete CSE 373, Autumn 2001
Sentinels • Use a header or dummy node to simplify the code. header header empty list CSE 373, Autumn 2001
Linked Lists in C++ IntListItr IntList • Weiss uses three classes to implement linked lists. IntListNode CSE 373, Autumn 2001
IntListNode class IntListNode { private: IntListNode (const int theData = 0, IntListNode * n = NULL) : data(theData), next(n) { } int data; IntListNode * next; friend class IntList; friend class IntListItr; }; • IntListNode represents one node of a list. CSE 373, Autumn 2001
IntListItr class IntListItr { public: IntListItr() : current(NULL) { } bool isPastEnd() const { return (current == NULL); } void advance() { if (!isPastEnd()) current = current->next; } const int retrieve() const { if (isPastEnd()) throw BadIterator(); return current->data; } CSE 373, Autumn 2001
private: IntListNode * current; IntListItr(IntListNode * theNode) : current(theNode) { } friend class IntList; } // class IntListItr class IntList { public: // constructors ... bool isEmpty() const; void makeEmpty(); IntListItr zeroth() const; ... void insert (const int x, const IntListItr & p); ... private: IntListNode *header; } CSE 373, Autumn 2001
IntList functions IntList::IntList() { header = new IntListNode; } bool IntList::isEmpty() const { return (header->next == NULL); } IntListItr IntList::first() const { return IntListItr(header->next); } IntListItr IntList::find(const int x) const { IntListNode *itr = header->next; while ((itr != NULL) && (itr->data != x)) itr = itr->next; return IntListItr(itr); } CSE 373, Autumn 2001