Top Banner
Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13- 140909-3 1
52

Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Jan 04, 2016

Download

Documents

Erik Ford
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

ListsChapter 65/14/15

Adapted from instructor slidesNyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson

Education, Inc. All rights reserved. 0-13-140909-3 1

Page 2: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Software Development (Review)

• Make it work…then make it pretty can result in dangerous code• Better to take a unified, consistent and logical approach• 5 Phases of the Software Development Lifecycle:

1. Requirements2. Design3. Implementation4. Testing/Integration5. Maintenance

• Waterfall Method• Agile/SCRUM Method• Prototyping

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All

rights reserved. 0-13-140909-3 2

Page 3: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Software Development (Review ctd)

• Need to decide what the actual problem is (which may or may not be what the customer/user asked for)

• How to approach:• Top Down Design

• Original problem divided into smaller, more manageable specific problems• Object Oriented Design

• Identify objects, their attributes and operations

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All

rights reserved. 0-13-140909-3 3

Page 4: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Abstract Data Type (ADT)…review

• An abstract data type is:1. A collection of data items (storage structures)2. Basic operations that can be performed on these items (algorithms)

• Called abstract because the represented data and the algorithms that operate on it are independent of the implementation (data abstraction)• Thinking about what can be done with the data, not how it is done

Page 5: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Chapter Contents6.1 List as an ADT6.2 An Array-Based Implementation of Lists6.3 An array Based Implementation of Lists with Dynamic Allocation6.4 Introduction to Linked Lists6.5 A Pointer-Based Implementation of Linked Lists in C++6.6 An Array-Based Implementation of Linked Lists

5

Page 6: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Chapter Objectives

• To study list as an ADT

• Build a static-array-based implementation of lists and note strengths, weaknesses

• Build a dynamic-array-based implementation of lists, noting strengths and weaknesses

• See need for destructor, copy constructor, assignment methods

• Take first look at linked lists, note strengths, weaknesses

• Study pointer-based implementation of linked lists

6

Page 7: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Consider Every Day Lists

• Groceries to be purchased• Job to-do list• List of assignments for a course• Dean's list

This guy has some pretty important lists

7

Page 8: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Properties of Lists

• Can have a single element• List of even prime numbers (2)

• Can have no elements• Names of delicious recipe which use kale

• There can be lists of lists• A list of the above lists

• We will look at the list as an abstract data type• Homogeneous• Finite length• Sequential elements

8

Page 9: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

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

9

Page 10: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Designing a List Class

• Should contain at least the following function members• Constructor• empty()• insert()• delete()• display()

• Implementation involves• Defining data members• Defining function members from design phase

10

Page 11: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Array-Based Implementation of Lists

• An array is a viable choice for storing list elements• Element are sequential• It is a commonly available data type• Algorithm development is easy

• Normally sequential orderings of list elements match with array elements

11

Page 12: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Implementing Operations• Constructor

• Static array allocated at compile time

• Empty• Check if size == 1

• Traverse• Use a loop from 0th element to size – 1

• Insert• Shift elements to

right of insertion point

• Delete• Shift elements back

12

Also adjust size up or

down

Also adjust size up or

down

Page 13: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Static Array

Use templatetemplate <class T>

class List

{

public:

List();

bool isEmpty() const;

bool insert(const T&, const int&);

bool remove(const int&);

void display(ostream&) const;

private:

T _items[CAPACITY]; // array to store list elements

int _size; // current size of the list stored in _items

};13

Page 14: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Template?

• By writing ‘template’ before a class definition, the class can be used with any data type

• Template <class T> could use any data type represented by T• T can be any of C++ defined data types (int, char, etc) or one that is

user-defined• Different ways to implement a template, can declare and implement

in one .h file• Better approach is to have template class definition in header file and

implementation in it’s own .cpp file• In this instance, will need to add the line:

• Template <class T> before each function header• Each function name is preceded with classname<T>::

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All

rights reserved. 0-13-140909-3 14

Page 15: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Static Array

• Constructortemplate <class T>List<T>::List() { _size = 0;}

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson

Education, Inc. All rights reserved. 0-13-140909-3 15

Page 16: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Static Array

• Displaytemplate <class T>void List<T>::display(ostream& out) const{ {

for(int i = 0; I < _size; ++i){

out << _items[i];if(i+1 < _size){

out << “ “;}

}}

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson

Education, Inc. All rights reserved. 0-13-140909-3 16

Page 17: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Static Array• Inserttemplate <class T>bool List<T>::insert(const T& item, const int& position){ if(_size == CAPACITY) return false; if(position < 0 || position > _size) return false; //shift elements to the right to make space for the new element for(int i = size; I > position; ==i) { _items[i] = _items[i-1]’ } //put the new element in the correct position _items[position] = item;

//increment the size of the current list ++_size; return true}

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson

Education, Inc. All rights reserved. 0-13-140909-3 17

Page 18: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

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

18

Page 19: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Dynamic-Allocation for List Class• Changes required in data members

• Eliminate const declaration for CAPACITY• Add variable 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()

19

Page 20: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Static Array

Use templatetemplate <class T>

class List

{

public:

List();

bool isEmpty() const;

bool insert(const T&, const int&);

bool remove(const int&);

void display(ostream&) const;

private:

T _items[CAPACITY]; // array to store list elements

int _size; // current size of the list stored in _items

};20

Page 21: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

List Class with Dynamic Array

template <class T>

class List

{

public:

List();

bool isEmpty() const;

bool insert(const T&, const int&);

bool remove(const int&);

void display(ostream&) const;

private:

T* _items; // array to store list elements

int _size; // current size of the list stored in _items

int_capacity; //current amount of allocated memory

};

21

Page 22: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Dynamic-Allocation for List Class

Dynamic array constructortemplate <class T>List<T>::List(const int& capacity=MAX_SIZE) { _capacity = capacity; _items = new(nothrow) T[_capacity]; _size = 0; assert(_items != 0);}

22

Static array constructortemplate <class T>List<T>::List() { _size = 0;}

Page 23: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

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

23

Page 24: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

New Functions Needed

• Destructor• 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

template <class T>List<T>::~List() { delete [] _items;}

24

Page 25: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

New Functions Needed• Copy Constructor – makes a "deep copy" of an object

• When argument passed as value parameter• When function returns a local object• When temporary storage of object needed• When object initialized by another in a declaration

• If copy is not made, observe results(aliasing problem, "shallow" copy)

25

Page 26: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

New Functions Needed• Assignment operator

• Default assignment operator makes shallow copy• Can cause memory leak, dynamically-allocated memory has nothing

pointing to it• Function would essentially create a new array and copy the element

values of the existing array, into the new array

26

Page 27: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Notes on Class Design*****

If a class allocates memory at run time using the new keyword, it should provide …

• A destructor• A copy constructor• An assignment operator

27

Page 28: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Future Improvements to Our List Class• Problem 1: Array used has fixed capacity

Solution:• If larger array needed during program execution• Allocate, copy smaller array to the new one

• Problem 2: Class bound to one type at a timeSolution:

• Create multiple List classes with differing names• Use class template

28

Page 29: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Recall Inefficiency of Array-Implemented List

• insert() and erase() functions inefficient for dynamic lists • Those that change frequently • Those with many insertions and deletions

So … We look for an alternative implementation.

29

Page 30: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Linked List

For the array-based implementation:1. First element is at location 02. Successor of item at location i is at location

i + 1

3. End is at location size – 1

Fix:4. Remove requirement that list elements be stored in consecutive

location.5. But then need a "link" that connects each element to its successor

30

Linked Lists !!Linked Lists !!

Page 31: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Linked List

• Linked list NODE contains• Data part – stores an element of the list• Next part – stores link/pointer to next element

(when no next element, null value)

31

Page 32: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Linked Lists Operations

• Construction: first = null_value;• Empty: first == null_value?• Traverse

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

32

Page 33: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Linked Lists Operations

• Traverse (ctd)• set ptr = ptr->next• process ptr->data• Continue until ptr == null

33

Pseudocodeptr = firstwhile( ptr != null){ process node data ptr = ptr->next}

Page 34: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Operations: Insertion

• Insertion • To insert 20 after 17• Need address of item before point of insertion• predptr points to the node containing 17• Get 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

34

Page 35: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Operations: Insertion

• 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

• In all cases, no shifting of list elements is required !

35

Page 36: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Operations: Deletion

• Delete node containing 22 from list.• Suppose ptr points to the node to be deleted• predptr points to its predecessor (the 20)

• 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.

36

Page 37: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

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

37

Page 38: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Linked Lists - Disadvantages• Overhead of links:

• used only internally, pure overhead

• If dynamic, must provide • destructor• copy constructor• Assignment operator

• No longer have direct access to each element of the list• Many sorting algorithms need direct access• Binary search needs direct access

• Access of nth item now less efficient • must go through first element, and then second, and then third, etc.

38

Page 39: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

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

39

Array Linked List

a[size++] = value; Get a new node; set data part = value next part = null_valueIf 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 partThis is the inefficient part

Page 40: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Using C++ Pointers and Classes

• To Implement Nodes class Node{ public:

T 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

40

Page 41: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Working with Nodes• Declaring pointers

Node * ptr; 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 orptr->data and ptr->next

41

Page 42: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Class List

template <class T> class List{ private: class Node { public: T data; Node * next; }; . . .}

42

• data is public inside class Node

• class Node is private inside List

• data is public inside class Node

• class Node is private inside List

Page 43: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Data Members for Linked-List Implementation

• A linked list will be characterized by**:• A pointer to the first node in the list.• Each node contains a pointer to the next node in the list• The last node contains a null pointer

• As a variation first may • be a structure• also contain a count of the elements in the list

43

Page 44: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Function Members for Linked-List Implementation

• Constructor• Make first a null pointer and • set mySize to 0

• Destructor• Nodes are dynamically allocated by new• Default destructor will not specify the delete• All the nodes from that point on would be "marooned memory"• A destructor must be explicitly implemented to do the delete

44

0

Page 45: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Function Members for Linked-List Implementation

45

Shallow CopyShallow Copy

Page 46: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Function Members for Linked-List Implementation

• Copy constructor for deep copy• By default, when a copy is made of a List object, it only gets the head

pointer• Copy constructor will make a new linked list of nodes to which copy will

point

• Assignment operator ( = ) is the same process

46

Page 47: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Array-Based Implementation of Linked Lists

• Node structurestruct NodeType{ DataType data; int next;};

•const int NULL_VALUE = -1;// Storage Poolconst int NUMNODES = 2048;NodeType node [NUMNODES];int free;

47

Page 48: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Array-Based Implementation of Linked Lists

• Given a list with names

• Implementation wouldlook like this

48

Page 49: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Array-Based Implementation of Linked Lists

• To traverseptr = first;while (ptr != NULL_VALUE){

// process data at node[ptr].dataptr = node[ptr].next;

}

49

Page 50: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Organizing Storage Pool

• In the array• Some locations are storing nodes of the list• Others are free nodes, available for new data

• Could initially link all nodes as free

50

Page 51: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Organizing Storage Pool

• Then use nodes as required for adds and inserts• Variable free points to beginning of linked nodes of storage pool

51

Page 52: Lists Chapter 6 5/14/15 Adapted from instructor slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,

Organizing Storage Pool

• Links to actual list and storage pool maintained as new data nodes are added and deleted

52