Review Dr. Yingwu Zhu. Outline ADT concept C++ Class List with class implementation.

Slides:



Advertisements
Similar presentations
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Advertisements

Lists: An internal look
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Chapter Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Class and Objects.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Data Structures Using C++ 2E
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Exam Review 5/28/15. Software Development (Review)  Make it work…then make it pretty can result in dangerous code  Better to take a unified, consistent.
Pointers OVERVIEW.
Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
A first look an ADTs Solving a problem involves processing data, and an important part of the solution is the careful organization of the data In order.
More Linking Up with Linked Lists Chapter 11 5/19/2015 Adopted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++,
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Brief Review.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter Lists Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2010.
Programming Techniques Classes II Important Class Features Spring 2009.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lists Chapter.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Data Structure & Algorithms
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
LINKED LISTS.
Memory Management.
Pointers and Linked Lists
Brief Review of ADTs and Class Implementation
Linked Lists Chapter 6 Section 6.4 – 6.6
Andy Wang Object Oriented Programming in C++ COP 3330
A First C++ Class – a Circle
Dr. Bernard Chen Ph.D. University of Central Arkansas
Chapter 4 Linked Lists.
More about OOP and ADTs Classes
Array Lists Chapter 6 Section 6.1 to 6.3
Brief Review of ADTs and Class Implementation
More about OOP and ADTs Classes
Chapter 16 Linked Structures
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Dynamic allocation (continued)
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Presentation transcript:

Review Dr. Yingwu Zhu

Outline ADT concept C++ Class List with class implementation

3 What is ADT? Abstract Data Type ADT = data items + operations on the data Implementation of ADT – Storage/data structures to store the data – Algorithms for the operations, i.e., how to do it

C++ Classes Structs vs. Classes

5 Structs and Classes Similarities Essentially the same syntax Both are used to model objects with multiple attributes (characteristics) – represented as data members – also called fields Thus, both are used to process non- homogeneous data sets.

6 Structs vs. Classes Differences No classes in C Members public by default Can be specified private Both structs and classes in C++ Structs can have members declared private Class members are private by default Can be specified public

7 Advantages in C++ Classes C++ classes model objects which have: – Attributes represented as data members – Operations represented as functions (or methods) Leads to object oriented programming – Objects are self contained – "I can do it myself" mentality

8 Class Declaration Syntax class ClassName { public: Declarations of public members private: Declarations of private members };

9 Designing a Class Data members normally placed in private: section of a class (information hiding) Function members usually in public: section (exported for external use)

10 Class Libraries Class declarations placed in header file – Given.h extension – Contains data items and prototypes Implementation file – Same prefix name as header file – Given.cpp extension Programs which use this class library called client/driver programs

11 Translating a Library

12 Example of User-Defined Time Class Now we create a Time class (page 150) – Actions done to Time object, done by the object itself Note interface for Time class object, Fig. 4.2 Fig. 4.2 – Data members private – inaccessible to users of the class – Information hiding class Time { private: unsigned myHours, myMinutes; char myAMorPM; public: … };

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Constructors Understanding Constructors, p – Initialize data members – Optional: allocate memory Note constructor definition in Time.cpp example (p161) example Syntax ClassName::ClassName (parameter_list) : member_initializer_list { // body of constructor definition }

14 Constructors Time::Time() { myHours = 0; myMinutes = 0; myAMorPM = ‘A’; } Time::Time(unsigned h, unsigned m, char c) : myHours(h), myMinutes(m), myAMorPM(c) { } Data member initialization

15 Overloading Functions Note existence of multiple functions with the same name Time(); Time(unsigned initHours, unsigned initMinutes, char initAMPM); – Known as overloading Compiler compares numbers and types of arguments of overloaded functions – Checks the "signature" of the functions

16 Default Arguments Possible to specify default values for constructor arguments Time(unsigned initHours = 12, unsigned initMinutes = 0, char initAMPM = 'A'); Consider Time t1, t2(5), t3(5,30), t4(5,30,'P');

17 Copy Operations(p166) During initialization Time t = bedTime During Assignment t = midnight;

18 Overloading Operators Same symbol can be used more than one way Operator , function: operator  () Two cases – If  is a function member: a  b  a.operator  (b) – Otherwise, a  b  operator  (a,b) Operators: +,-,*,/ Operators: >

19 Redundant Declarations Note use of #include "Time.h" in – Time.cpp Time.cpp – Client program Client program Causes "redeclaration" errors at compile time Solution is to use conditional compilation – Use #ifndef and #define and #endif compiler directives#ifndef and #define #endif

20 Pointers to Class Objects Possible to declare pointers to class objects Time * timePtr = &t; Access with timePtr->getMilTime() or (*timePtr).getMilTime()

21 The this Pointer Every class has a keyword, this – a pointer whose value is the address of the object – Value of *this would be the object itself

22 Exercise Use what we have learned to Implement a polynomial class in the form of ax+b, coefficients a and b are integers. – Constructor – Overload operator+ – Overload operator<<

24 Example for class “ax+b” //poly.h: header file #include using namespace std; #ifndef _POLY_H // avoid redundant declarations #define _POLY_H class Poly { private: int m_ca; //coefficient a int m_cb; public: Poly(int a, int b) : m_ca(a), m_cb(b) { }; //constructor void display(ostream& out) const; //for operator << overloading Poly operator+(const Poly& po); //overloading + }; //do not forget to put ; !!!! ostream& operator<<(ostream& out, const Poly& po); //overloading << #endif

25 Example: ax+b //poly.cpp: implementation file #include “poly.h” using namespace std; void Poly::display(ostream& out) const { out m_ca + po.m_ca; //what is “this”? Do we need it here? c.m_cb = m_cb + po.m_cb; return c; } ostream& operator<<(ostream& out, const Poly& po) { po.display(out); return out; }

List with Class Implementation List as an ADT 3 different implementations – Static array-based – Dynamic array-based – Linked-list based

27 Properties of Lists Can have a single element Can have no elements  empty! There can be lists of lists We will look at the list as an abstract data type – Homogeneous – Finite length – Sequential elements

28 Basic Operations Construct an empty list Determine whether or not empty Insert an element into the list Delete an element from the list Traverse (iterate through) the list to – Modify – Output – Search for a specific value – Copy or save – Rearrange

29 Designing a List Class Should contain at least the following function members – Constructor – empty() – insert() – delete() – display() Implementation involves – Choosing data structures to store data members – Choosing algorithms to implement function members

Impl. 1: Static Array Use a static array to hold list elements Easy to manipulate arrays for implementing operations Natural fit for mapping list elements to array elements

Design What data members? What operations?

32 const int CAPACITY = 1000; //for what purpose? typedef int ElementType; //for what purpose? class List { private: int size; //# of elements ElementType array[CAPACITY]; public: … };

33 Implementing Operations Constructor – Static array allocated at compile time. No need to allocate explicitly! Empty – Check if size == 0 Traverse – Use a loop from 0 th element to size – 1 Insert – Shift elements to right of insertion point Delete – Shift elements back Also adjust size up or down

34 List Class with Static Array - Problems Stuck with "one size fits all" – Could be wasting space – Could run out of space Better to have instantiation of specific list specify what the capacity should be Thus we consider creating a List class with dynamically-allocated array

Impl. 2: Using Dynamic Arrays Allow List objects to specify varied sizes

36 Dynamic-Allocation for List Class Now possible to specify different sized lists cin >> maxListSize; List aList1(maxListSize); List aList2(500);

37 Dynamic-Allocation for List Class Changes required in data members – Eliminate const declaration for CAPACITY – Add data member to store capacity specified by client program – Change array data member to a pointer – Constructor requires considerable change Little or no changes required for – empty() – display() – erase() – insert()

38 typedef int ElementType; class List { private: int mySize; //# of elements int myCapacity; ElementType *myArray; public: List (int cap); };

What needs to be changed? Constructor Addition of other functions to deal with dynamically allocated memory – Destructor – Copy constructor (won’t be discussed here) – Assignment operator (won’t be discussed here)

Constructor Two tasks – Data member initialization – Dynamically allocate memory //constructor List::List(int cap) : mySize(0), myCapacity(cap) { myArray = new int[cap]; //allocate memory assert(myArray != 0); //need #include }

41 Destructor Needed! When class object goes out of scope, the pointer to the dynamically allocated memory is reclaimed automatically The dynamically allocated memory is not The destructor reclaims dynamically allocated memory

Destructor The default destructor needs to be overrided! De-allocate memory you allocated previously; otherwise raises memory leak problem! List::~List() { delete [] myArray; }

Problems Array capacity cannot be changed during running time (execution)! Insertion & deletion are not efficient! – Involve element shifting

Impl. 3: Using Linked-Lists Are able to address the two problems faced by array-based solutions

45 Linked List Linked list nodes contain – Data part – stores an element of the list – Next part – stores link/pointer to next element (when no next element, null value)

Basic Operations Traversal Insertion Deletion

47 Traversal Initialize a variable ptr to point to first node Process data where ptr points

48 Traversal (cont.) set ptr = ptr->next, process ptr- >data Continue until ptr == null

49 Insertion – To insert 20 after 17 – Need address of item before point of insertion – predptr points to the node containing 17 – Create a new node pointed to by newptr and store 20 in it – Set the next pointer of this new node equal to the next pointer in its predecessor, thus making it point to its successor. – Reset the next pointer of its predecessor to point to this new node 20 newptr predptr

50 Insertion Note: insertion also works at end of list – pointer member of new node set to null Insertion at the beginning of the list – predptr must be set to first – pointer member of newptr set to that value – first set to value of newptr  Note: In all cases, no shifting of list elements is required !

51 Operations: Deletion Delete node containing 22 from list. – Suppose ptr points to the node to be deleted – predptr points to its predecessor (the 17) Do a bypass operation : – Set the next pointer in the predecessor to point to the successor of the node to be deleted – Deallocate the node being deleted. predptr ptr To free space

# 1 Lesson in Pointers Before operating on an pointer, first check if it is null! if (ptr) { //do sth. meaningful }

53 Linked Lists - Advantages Access any item as long as external link to first item maintained Insert new item without shifting Delete existing item without shifting Can expand/contract as necessary

54 Linked Lists - Disadvantages Overhead of links: – used only internally, pure overhead If dynamic, must provide – destructor – copy constructor (but not here!) No longer have direct access to each element of the list – Many sorting algorithms need direct access – Binary search needs direct access Access of n th item now less efficient – must go through first element, and then second, and then third, etc.

55 Linked Lists - Disadvantages List-processing algorithms that require fast access to each element cannot be done as efficiently with linked lists. Consider adding an element at the end of the list ArrayLinked List a[size++] = value; Get a new node; set data part = value next part = null_value If list is empty Set first to point to new node. Else Traverse list to find last node Set next part of last node to point to new node. This is the inefficient part

56 Using C++ Pointers and Classes To Implement Nodes class Node { public: DataType data; Node * next; }; Note: The definition of a Node is recursive – (or self-referential) It uses the name Node in its definition The next member is defined as a pointer to a Node

57 Working with Nodes Declaring pointers Node* ptr; or typedef Node* NodePointer; NodePointer ptr; Allocate and deallocate ptr = new Node;delete ptr; Access the data and next part of node (*ptr).data and (*ptr).next or ptr->data and ptr->next

58 Working with Nodes Note data members are public This class declaration will be placed inside another class declaration for List (private section), p296 class Node { public: DataType data; Node * next; };

59 typedef int ElementType; class List { private: class Node { public: ElementType data; Node * next; }; typedef Node * NodePointer; … Implementing List with Linked-Lists data is public inside class Node class Node is private inside List data is public inside class Node class Node is private inside List

Design & Impl. Add data members Add member functions

Class List #ifndef _LIST_H #define _LIST_H typedef int ElementType; class List { private: class Node { public: ElementType data; Node* next; }; typedef Node* NodePointer; private: NodePointer first; public: List(); ~List(); void insert(ElementType x); void delete(ElementType x); }; #endif

Implementing Constructor Destructor Operation: insert() Operation: delete()

Exercises Implement Stack and Queue classes with different implementations.

64 Stack Design and Implement a Stack class 3 options – Static array – Dynamic array – Linked list

65 Stack.h typedef int DataType; class Stack { public: Stack(); Stack(const Stack& org); void push(const DataType& v); void pop(); DataType top() const; ~Stack(); private: class Node { public: DataType data; Node* next; Node(DataType v, Node* p) : data(v), next(0) { } }; typedef Node* NodePtr; NodePtr myTop; };

66 Queue Design and Implement a Queue class 3 options – Static array – Dynamic array – Linked list

67 Queue.h typedef int DataType; class Queue { public: //constructor //… member functions private: class Node { public: DataType data; Node* next; Node(DataType v, Node* p) : data(v), next(0) { } }; typedef Node* NodePtr; NodePtr myFront, myback; };