Lists 1 Topics List as an ADT An

  • Slides: 46
Download presentation
Lists 1

Lists 1

Topics • List as an ADT • An Array-Based Implementation of Lists • An

Topics • List as an ADT • An Array-Based Implementation of Lists • An array Based Implementation of Lists with Dynamic Allocation • Linked Lists • A Pointer-Based Implementation of Linked Lists in C++ 2

Objectives • To study list as an ADT • Build a static-array-based implementation of

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 o See need for destructor, copy constructor, assignment methods • Take first look at linked lists, note strengths, weaknesses • Study pointer-based implementation of linked lists 3

Consider Every Day Lists • • Groceries to be purchased Job to-do list List

Consider Every Day Lists • • Groceries to be purchased Job to-do list List of assignments for a course Dean's list 4

Properties of Lists • Can have a single element • Can have no elements

Properties of Lists • Can have a single element • Can have no elements • There can be lists of lists • We will look at the list as an abstract data type o Homogeneous o Finite length o Sequential elements 5

Basic Operations • • • Construct an empty list Determine whether or not empty

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 o o Modify Output Search for a specific value Copy or save Rearrange 6

Designing a List Class • Should contain at least the following function members o

Designing a List Class • Should contain at least the following function members o o o Constructor empty() insert() delete() display() • Implementation involves o Defining data members o Defining function members from design phase 7

Array-Based Implementation of Lists • An array is a viable choice for storing list

Array-Based Implementation of Lists • An array is a viable choice for storing list elements o Elemenst are sequential o It is a commonly available data type o Algorithm development is easy • Normally sequential orderings of list elements match with array elements 8

Implementing Operations • Constructor o Static array allocated at compile time • Empty o

Implementing Operations • Constructor o Static array allocated at compile time • Empty o Check if size == 0 • Traverse o Use a loop from 0 th element to size – 1 • Insert o Shift elements to right of insertion point • Delete Also adjust size up or down o Shift elements back 9

List Class with Static Array • Must deal with issue of declaration of CAPACITY

List Class with Static Array • Must deal with issue of declaration of CAPACITY o Specify the CAPACITY as a static const o or choose to declare outside class • Use template mechanism template <class T> • T array[CAPACITY]; 10

List Class Example • See List Code link on web site. o Use of

List Class Example • See List Code link on web site. o Use of templates o Moving elements for insert and erase o Using operator<< as a non-friend function 11

List Class with Static Array Problems • Stuck with "one size fits all" o

List Class with Static Array Problems • Stuck with "one size fits all" o Could be wasting space o 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 12

Dynamic-Allocation for List Class • Changes required in data members o Eliminate const declaration

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

Dynamic-Allocation for List Class • See List Code on class web site. 14

Dynamic-Allocation for List Class • See List Code on class web site. 14

Dynamic-Allocation for List Class • Now possible to specify different sized lists cin >>

Dynamic-Allocation for List Class • Now possible to specify different sized lists cin >> max. List. Size; List a. List 1 (max. List. Size); List a. List 2 (500); 15

New Functions Needed • Destructor o When class object goes out of scope the

New Functions Needed • Destructor o When class object goes out of scope the statically allocated memory is reclaimed automatically o But the dynamically allocated memory must be explicitly reclaimed o The destructor reclaims dynamically allocated memory 16

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

New Functions Needed • Copy Constructor – makes a "deep copy" of an object o o 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) 17

New Functions Needed • Assignment operator o Default assignment operator makes shallow copy o

New Functions Needed • Assignment operator o Default assignment operator makes shallow copy o Can cause memory leak, dynamically-allocated memory has nothing pointing to it 18

Notes on Class Design If a class allocates memory at run time using the

Notes on Class Design If a class allocates memory at run time using the new, then it should provide … • A destructor • A copy constructor • An assignment operator 19

Future Improvements to Our List Class • Problem: Arrays have fixed capacity whether static

Future Improvements to Our List Class • Problem: Arrays have fixed capacity whether static or dynamic Solution: o If larger array needed during program execution o Allocate, copy smaller array to the new one – YUCK! 20

Recall Inefficiency of Array-Implemented List • insert() and erase() functions inefficient for dynamic lists

Recall Inefficiency of Array-Implemented List • insert() and erase() functions inefficient for dynamic lists o Those that change frequently o Those with many insertions and deletions So … We look for an alternative implementation. 21

Linked List For the array-based implementation: 1. First element is at location 0 2.

Linked List For the array-based implementation: 1. First element is at location 0 2. Successor of item at location i is at location i + 1 3. End is at location size – 1 Fix: 1. Remove requirement that list elements be stored in consecutive locations. 2. But then need a "link" that connects each element to its successor. Linked Lists !! 22

Linked List • Linked list nodes contain o Data part – stores an element

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

Linked Lists Operations • Construction: first = null_value; • Empty: first == null_value? •

Linked Lists Operations • Construction: first = null_value; • Empty: first == null_value? • Traverse o Initialize a variable ptr to point to first node o Process data where ptr points 24

Linked Lists Operations • Traverse (ctd) o set ptr = ptr->next, process ptr->data o

Linked Lists Operations • Traverse (ctd) o set ptr = ptr->next, process ptr->data o Continue until ptr == null 25

Operations: Insertion predptr • Insertion newptr 20 o To insert 20 after 17 o

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

Operations: Insertion • Note: insertion also works at end of list o pointer member

Operations: Insertion • Note: insertion also works at end of list o pointer member of new node set to null • Insertion at the beginning of the list o predptr must be set to first o pointer member of newptr set to point to first set to value of newptr Note: In all cases, no shifting of list elements is required ! 27

Operations: Deletion predptr • Delete node containing 22 from list. To free space o

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

Linked Lists - Advantages • Access any item as long as external link to

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 29

Linked Lists Disadvantages • Overhead of links: o used only internally, pure overhead •

Linked Lists Disadvantages • Overhead of links: o used only internally, pure overhead • Must provide o destructor o copy constructor o assignment operator • No longer have direct access to each element of the list o Many sorting algorithms need direct access o Binary search needs direct access • Access of nth item now less efficient o must go through first element, and then second, and then third, etc. 30

Linked Lists - Disadvantages • List-processing algorithms that require fast access to each element

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 Array a[size++] = value; This is the inefficient part Linked List 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 31 point to new node.

First look at linked structures • See struct node example code for web site.

First look at linked structures • See struct node example code for web site. • A Node is a template-based struct. • This demonstrates some basic operations on lists – insert at front, at end, and interior. Traverse the list and do garbage collection. • Next we look at how to do all this with classes. 32

Using C++ Pointers and Classes • To Implement Nodes class Node { public: Data.

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

Working with Nodes • Declaring pointers Node * ptr; or typedef Node * Node.

Working with Nodes • Declaring pointers Node * ptr; or typedef Node * Node. Pointer; Node. Pointer 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 34

Working with Nodes • Note data members are public class Node { public: Data.

Working with Nodes • Note data members are public class Node { public: Data. Type data; Node * next; }; • This class declaration will be placed inside another class declaration for List • The data members data and next of class Node will be public inside the List class o will be accessible to the member and friend functions of List o will be private outside the class o Done in this manner, the Node class does not need to provide setters and getters 35

Class List template <class Element. Type> class List { • data is public inside

Class List template <class Element. Type> class List { • data is public inside private: class Node { • class Node is private public: inside List Element. Type data; Node * next; }; typedef Node * Node. Pointer; . . . 36

Data Members for Linked-List Implementation • A linked list will be characterized by: o

Data Members for Linked-List Implementation • A linked list will be characterized by: o A pointer to the first node in the list. o Each node contains a pointer to the next node in the list o The last node contains a null pointer • As a variation first may o be a structure • could contain a count of the elements in the list • or other useful info 37

Function Members for Linked-List Implementation • Constructor o Make first a null pointer and

Function Members for Linked-List Implementation • Constructor o Make first a null pointer and o set my. Size to 0 • Destructor o Nodes are dynamically allocated by new o Default destructor will not specify the delete o All the nodes from that point on would be "marooned memory" o A destructor must be explicitly implemented to do the delete 0 38

Function Members for Linked-List Implementation Shallow Copy • Copy constructor for deep copy o

Function Members for Linked-List Implementation Shallow Copy • Copy constructor for deep copy o By default, when a copy is made of a List object, it only gets the head pointer o Copy constructor will make a new linked list of nodes to which copy will point 39

Linked List Example Class • Examine linked list code sample found on web site.

Linked List Example Class • Examine linked list code sample found on web site. 40

What is a Circular Linked List? A circular linked list is a list in

What is a Circular Linked List? A circular linked list is a list in which every node has a successor; the “last” element is succeeded by the “first” element. 41

External Pointer to the Last Node 42

External Pointer to the Last Node 42

What is a Doubly Linked List? A doubly linked list is a list in

What is a Doubly Linked List? A doubly linked list is a list in which each node is linked to both its successor and its predecessor. 43

Linking the New Node into the List 44

Linking the New Node into the List 44

Deleting from a Doubly Linked List 45

Deleting from a Doubly Linked List 45

What are Header and Trailer Nodes? • A Header Node is a node at

What are Header and Trailer Nodes? • A Header Node is a node at the beginning of a list that contains a key value smaller than any possible key. • A Trailer Node is a node at the end of a list that contains a key larger than any possible key. • Both header and trailer are placeholding nodes used to simplify list processing. 46