Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.

Similar presentations


Presentation on theme: "1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures."— Presentation transcript:

1

2 1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures

3 ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators n ResetList n GetNextItem change state observe state process all

4 3 class SortedType MakeEmpty ~SortedType DeleteItem. InsertItem SortedType RetrieveItem GetNextItem ‘C’ ‘L’ ‘X’ Private data: length 3 listData currentPos

5 4 What is a Circular Linked List? l A circular linked list is a list in which every node has a successor; the “last” element is succeeded by the “first” element. ‘B’ ‘C’ ‘L’‘T’ ‘V’ ‘Y’ listData

6 5 Circularly Linked List l We can keep track of the list by just using one pointer, the pointer pointing to the last element of the list l In this way, we can add at the back (queue rules) using the rear pointer directly instead of writing a loop until you hit the NULL pointer l We can also reach the first element in one step(How?) l What else is different?

7 6 Circularly Linked List l RetrieveItem,InsertItem,DeleteItem all require search. We can write a general search function to help all of these functions l FindItem accepts item and returns location, predLoc and found l What if we want to go both ways?

8 7 ‘A’ ‘C’ ‘F’ ‘T’ ‘Z’ What is a Doubly Linked List? l A doubly linked list is a list in which each node is linked to both its successor and its predecessor. listData

9 8 Each node contains two pointers template struct NodeType { ItemType info; // Data member NodeType * back; // Pointer to predecessor NodeType * next; // Pointer to successor };. back. info. next 3000 ‘A’ NULL

10 9 Doubly Linked List l The doubly linked list is a linear list. Its first node has the back pointer set to NULL and its last node has the next pointer as NULL l We can traverse this list in both directions. Thus we are able to print “lowest to highest” as well as “highest to lowest” members l Doubly linked list is more difficult to maintain because it has more pointers

11 10 Doubly Linked List l For example, consider the doubly linked list shown and determine all the pointers that will be used and/or moved if we delete ‘C’ ‘A’ ‘C’ ‘F’ ‘T’ ‘Z’ listData

12 11 What are Header and Trailer Nodes? l A Header Node is a node at the beginning of a list that contains a key value smaller than any possible key. l A Trailer Node is a node at the end of a list that contains a key larger than any possible key. l Both header and trailer are placeholding nodes used to simplify list processing. listData INT_MIN 5 8 13 INT_MAX

13 12 Why Header and Trailer Nodes? l So that we never delete or add things before the starting node or after the last node l Thus we get rid of the special cases that we had to write l A list of names can have a start node “AAAAAAAA” and last node as “ZZZZZZZZ”

14 13 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of stack items can take place only at the top of the stack. l A stack is a LIFO “last in, first out” structure.

15 Stack ADT Operations l MakeEmpty -- Sets stack to an empty state. l IsEmpty -- Determines whether the stack is currently empty. l IsFull -- Determines whether the stack is currently full. l Push (ItemType newItem) -- Adds newItem to the top of the stack. l Pop (ItemType& item) -- Removes the item at the top of the stack and returns it in item. 14

16 15 class StackType StackType MakeEmpty Pop Push IsFull IsEmpty Private data: topPtr ~StackType 20 30

17 16 What happens... l When a function is called that uses pass by value for a class object like our dynamically linked stack? StackType MakeEmpty Pop Push IsFull IsEmpty Private data: topPtr ~StackType 20 30

18 17 // FUNCTION CODE template void MyFunction( StackType SomeStack ) // Uses pass by value {.... } 17 Passing a class object by value

19 18 Pass by value makes a shallow copy 20 30 StackType MyStack; // CLIENT CODE. MyFunction( MyStack ); // function call Private data: 7000 6000 topPtr 7000 Private data: topPtr 7000 MyStack SomeStack shallow copy

20 19 Shallow Copy vs. Deep Copy l A shallow copy copies only the class data members, and does not copy any pointed-to data. l A deep copy copies not only the class data members, but also makes separately stored copies of any pointed-to data.

21 20 What’s the difference? l A shallow copy shares the pointed to data with the original class object. l A deep copy stores its own copy of the pointed to data at different locations than the data in the original class object.

22 21 Making a deep copy 20 30 Private data: 7000 6000 topPtr 7000 SomeStack 20 30 Private data: 5000 2000 topPtr 5000 MyStack deep copy

23 22 // FUNCTION CODE template void MyFunction( StackType SomeStack ) // Uses pass by value { ItemType item; SomeStack.Pop(item);... } WHAT HAPPENS IN THE SHALLOW COPY SCENARIO? 22 Suppose MyFunction Uses Pop

24 23 MyStack.topPtr is left dangling ? 30 StackType MyStack; // CLIENT CODE. MyFunction( MyStack ); Private data: topPtr 6000 MyStack SomeStack shallow copy Private data: 7000 6000 topPtr 7000

25 24 MyStack.topPtr is left dangling ? 30 Private data: topPtr 6000 MyStack SomeStack shallow copy Private data: 7000 6000 topPtr 7000 NOTICE THAT NOT JUST FOR THE SHALLOW COPY, BUT ALSO FOR ACTUAL PARAMETER MyStack, THE DYNAMIC DATA HAS CHANGED!

26 25 As a result... l This default method used for pass by value is not the best way when a data member pointer points to dynamic data. l Instead, you should write what is called a copy constructor, which makes a deep copy of the dynamic data in a different memory location.

27 26 More about copy constructors l When there is a copy constructor provided for a class, the copy constructor is used to make copies for pass by value. l You do not call the copy constructor. l Like other constructors, it has no return type. l Because the copy constructor properly defines pass by value for your class, it must use pass by reference in its definition.

28 27 Copy Constructor l Copy constructor is a special member function of a class that is implicitly called in these three situations: n passing object parameters by value, n initializing an object variable in a declaration, n returning an object as the return value of a function. n It does not run when you assign an object to another

29 // DYNAMICALLY LINKED IMPLEMENTATION OF STACK class StackType { public: StackType( ); // Default constructor. // POST: Stack is created and empty. StackType( const StackType& anotherStack ); // Copy constructor. // Implicitly called for pass by value.... ~StackType( ); // Destructor. // POST: Memory for nodes has been deallocated. private: NodeType* topPtr ; }; 28

30 29 CLASS CONSTRUCTOR CLASS COPY CONSTRUCTOR CLASS DESTRUCTOR Classes with Data Member Pointers Need

31 // COPY CONSTRUCTOR, Copying from anotherstack StackType:: StackType( const StackType& anotherStack ) { NodeType* ptr1 ; NodeType* ptr2 ; if ( anotherStack.topPtr == NULL ) topPtr = NULL ; else // allocate memory for first node { topPtr = new NodeType ; topPtr->info = anotherStack.topPtr->info ; ptr1 = anotherStack.topPtr->next ; ptr2 = topPtr ; while ( ptr1 != NULL )// deep copy other nodes { ptr2->next = new NodeType; ptr2 = ptr2->next ; ptr2->info = ptr1->info ; ptr1 = ptr1->next ; } ptr2->next = NULL ; } } 30

32 31 What about the assignment operator? l The default method used for assignment of class objects makes a shallow copy. l If your class has a data member pointer to dynamic data, you should write a member function to overload the assignment operator to make a deep copy of the dynamic data. l Thus a=b will make a deep copy

33 32 Overloading Operators l C++ allows us to *redefine* the meaning of the relational operators in terms of the data members of a class l This redefinition is called overloading an operator l A simple example was covered in chapter 3

34 33 Overloading l class StrType l{l{ l public l:l: l bool operator == (StrType otherstring) const; l:l: l}l}

35 34 Overloaded == operator l bool StrType::operator == (strType otherstring) const l{l{ l int result; l result = std::strcmp(letters, otherstring.letters); l if (result == 0) l return true; l else l return false; l}l}

36 35 Overloading an Operator l How to use an overloaded operator? l Overloaded operators can only be used with data items that belong to user defined classes l StrType a; l StrType b; l if (a == b) cout<<“Yes indeed”<<endl; l else cout<<“Sorry! They are not equal”<<endl;

37 36 Another Example l //Overloading syntax example modified from original program at http://www.codeguru.com/cpp/tic/tic0127.shtmlhttp://www.codeguru.com/cpp/tic/tic0127.shtml l #include l using namespace std; l class Integer { l int i; l public: l Integer(int ii) l { i = ii; } l const Integer l operator+(const Integer& rv) const { l cout << "operator+" << endl; l return Integer(i + rv.i); l }

38 37 l Integer& l operator+=(const Integer& rv){ l cout << "operator+=" << endl; l i += rv.i; l return *this; l } l void display() l { l cout<<i<<endl; l } l };

39 38 Client Code l void main() { l cout << "built-in types:" << endl; l int i = 1, j = 2, k = 3; l k += i + j; l cout<<"k is now "<<k<<endl; l cout << "user-defined types:" << endl; l Integer I(1), J(2), K(3); l K += I + J; l cout<<"K is now "<<endl; l K.display(); l } ///:~

40 // DYNAMICALLY LINKED IMPLEMENTATION OF STACK class StackType { public: StackType( ); // Default constructor. StackType( const StackType& anotherStack ); // Copy constructor. void operator= ( StackType ); // Overloads assignment operator.... ~StackType( ); // Destructor. private: NodeType* topPtr ; }; 39

41 40 C++ Operator Overloading Guides 1All operators except these ::. sizeof ?: may be overloaded. 2At least one operand must be a class instance. 3You cannot change precedence, operator symbols, or number of operands. 4Overloading ++ and -- requires prefix form use by default, unless special mechanism is used. 5To overload these operators = ( ) [ ] member functions (not friend functions) must be used. 6An operator can be given multiple meanings if the data types of operands differ.

42 Using Overloaded Binary operator+ When a Member Function was defined myStack + yourStack myStack.operator+(yourStack) When a Friend Function was defined myStack + yourStack operator+(myStack, yourStack) 41

43 42 Composition and Inheritance l Classes are related in three ways l 1) Independent of one another l 2) One class is contained within another class (e.g. the array of ItemType class that was used to build stack ADT) l 3) One class may acquire the properties of another class. (A Derived class inherits properties of the base class)

44 43 Composition (containment) l Composition (or containment) means that an internal data member of one class is defined to be an object of another class type. A FAMILIAR EXAMPLE...

45 44 Private data value ComparedTo Print Initialize class ItemType ItemType Class Interface Diagram

46 45 Sorted list contains an array of ItemType SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem Private data: length info [ 0 ] [ 1 ] [ 2 ] [MAX_ITEMS-1] currentPos GetNextItem

47 46 Inheritance l Inheritance is a means by which one class acquires the properties--both data and operations--of another class. l When this occurs, the class being inherited from is called the Base Class. l The class that inherits is called the Derived Class. AN EXAMPLE...

48 47 Recall Definition of Queue l Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the rear), and elements are removed from the other end (the front). l A queue is a FIFO “first in, first out” structure.

49 Queue ADT Operations for a char Queue l MakeEmpty -- Sets queue to an empty state. l IsEmpty -- Determines whether the queue is currently empty. l IsFull -- Determines whether the queue is currently full. l Enqueue (char newItem) -- Adds newItem to the rear of the queue. l Dequeue (char& item) -- Removes the item at the front of the queue and returns it in item. 48

50 49 class QueType QueType ~QueType Enqueue Dequeue. Private Data: qFront qRear ‘C’‘Z’ ‘T’

51 // DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE class QueType { public: QueType( ); // CONSTRUCTOR ~QueType( ) ;// DESTRUCTOR bool IsEmpty( ) const; bool IsFull( ) const; void Enqueue( char item ); void Dequeue( char& item ); void MakeEmpty( ); private: NodeType* qFront; NodeType* qRear; }; 50

52 51 Inheritance l Now let us define a new class CountedQueue that inherits all data and properties of the Queue ADT l This new class adds enumeration to the queue by adding a new data member length and redefines enqueue and dequeue functions so that they can also increment and decrement length of the queue

53 52 // DERIVED CLASS CountedQue FROM BASE CLASS QueType class CountedQue : public QueType { public: CountedQue( ); void Enqueue( char newItem ); void Dequeue( char& item ); int LengthIs( ) const; // Returns number of items on the counted queue. private: int length; }; SAYS ALL PUBLIC MEMBERS OF QueType CAN BE INVOKED FOR OBJECTS OF TYPE CountedQue

54 53 class CountedQue QueType ~QueType Enqueue Dequeue. Private Data: qFront qRear ‘C’‘Z’ ‘T’ CountedQue LengthIs Enqueue Dequeue. Private Data: length 3

55 54 // Member function definitions for class CountedQue CountedQue::CountedQue( ) : QueType( ) { length = 0 ; } int CountedQue::LengthIs( ) const { return length ; }

56 void CountedQue::Enqueue( char newItem ) // Adds newItem to the rear of the queue. // Increments length. { length++; QueType::Enqueue( newItem ); } void CountedQue::Dequeue(char& item ) // Removes item from the rear of the queue. // Decrements length. { length--; QueType::Dequeue( item ); } 55


Download ppt "1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures."

Similar presentations


Ads by Google