108
Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Embed Size (px)

Citation preview

Page 1: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists

Briana B. Morrison

Adapted from Alan Eugenio &

William J. Collins

Page 2: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 2

Topics

Review from Lists Implementing a linked list

Doubly linked Dummy header node In an array

Function Implementation Dynamic memory management

Page 3: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 3

Abstract Model of a List Object

fro n t b ack

Page 4: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 4

A LIST, SOMETIMES CALLED A LINKED LIST, IS A

FINITE SEQUENCE OF ITEMS SUCH THAT:

1. ACCESSING OR MODIFYING AN ARBITRARY

ITEM IN THE SEQUENCE TAKES LINEAR

TIME;

2. GIVEN AN ITERATOR AT A POSITION IN

THE SEQUENCE, INSERTING OR DELETING

AT THAT POSITION TAKES CONSTANT

TIME.

Page 5: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 5

Model of a list object with links to next and previous element

fro nt b ac k

Page 6: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 6

THE STANDARD TEMPLATE

LIBRARY’S list CLASS IS THE OTHER

SEQUENTIAL CONTAINER CLASS

BESIDES vector AND deque.

Page 7: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 7

The List ADT

The list API documents the member function prototype as well as pre- and postconditions.

Page 8: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 8

CLASS list Constructors <list>

list();Create an empty list. This is the default constructor.

list(int n, const T&value = T());Create a list with n elements, each having a specified value. If the value argument is omitted, the elements

are filled with the default value for type T. Type T must have a default constructor, and the default value of type T is specified by the notation T().

list(T *first, T *last);Initialize the list, using the address range [first, last).

Page 9: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 9

The List Constructors provides three constructors to declare a list object.

0 .00 .0 0 .00 .0 0 .00 .0 0 .00 .0(a) lis t< d o ub le> realL is t(8)

8 :3 08 :3 0 8 :3 08 :3 0 8 :3 0 8 :3 0(b ) lis t< tim e24> tim eLis t(6, 8:30)

ar ray

(c ) lis t< s tring> s trL is t(s trA rr, s trA rr+ 3)l is tve c to r

Page 10: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 10

CLASS list Operations <list>

T& back();Return the value of the item at the rear of the list. Precondition: The list must contain at least one

element.

bool empty() const;Return true if the list is empty, false otherwise.

T& front();Return the value of the item at the front of the list. Precondition: The list must contain at least one

element.

Page 11: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 11

Using Front, Back and Empty

int arr[5] = {9, 2, 7, 3, 12};list<int> lst(arr,arr+5);

cout << lst.back( );lst.back( ) = 99;cout << lst.front( );lst.front( ) = 46;If (lst.empty( )) cout << “Empty”);

Page 12: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 12

CLASS list Operations <list>

void push_back(const T& value);Add a value at the rear of the list. Postcondition: The list has a new element at the

rear, and its size increases by 1.

void pop_back();Remove the item at the rear of the list. Precondition: The list is not empty. Postcondition: The list has a new element at the rear

or is empty.

Page 13: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 13

CLASS list Operations <list>

void push_front(const T& value);Add a value at the front of the list. Postcondition: The list has a new element at the

front, and its size increases by 1.

void pop_front();Remove the item at the front of the list. Precondition: The list is not empty. Postcondition: The list has a new element at the front

or is empty.

int size() const;Return the number of elements in the list.

Page 14: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 14

Using Push, Pop, and Size

int arr[5] = {9, 2, 7, 3, 12};list<int> lst(arr,arr+5);

lst.pop_back( );lst.push_back(99);lst.pop_front( );lst.push_front(11);cout << lst.size( );

Page 15: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 15

VERY IMPORTANT:

THE INDEX OPERATOR, operator[ ], IS

NOT AVAILABLE IN THE list CLASS!

Page 16: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 16

THIS OMISSION MAGNIFIES THE

VALUE OF ITERATORS. BASICALLY,

TO GET ANYWHERE IN A list, AN

ITERATOR IS NEEDED. THE

ITERATION MAY START AT THE

FRONT OR BACK, WHICHEVER IS

CLOSER TO THE POSITION SOUGHT.

Page 17: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 17

CLASS list Operations <list>

iterator begin();Returns an iterator that references the first position

(front) of the list. If the list is empty, the iterator value end() is returned.

const_iterator begin();Returns a const_iterator that points to the first position (front) of a constant list. If the list is empty, the

const_iterator value end() is returned.

Page 18: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 18

CLASS list Operations <list>

iterator end();Returns an iterator that signifies a location immediately out of the range of actual elements. A program must

not dereference the value of end() with the * operator.

const_iterator end();Returns a const_iterator that signifies a location

immediately out of the range of actual elements in a constant list. A program must not dereference the value of end() with the * operator.

Page 19: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 19

Using Iterators To declare an iterator:

list<int>::iterator listIter;

list<string>::iterator iter; Using an iterator:

list<int> intList;

listIter = intList.begin(); //initialize

listIter = intList.end(); //past end of list

Page 20: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 20

CLASS list Operations <list>

void erase(iterator pos);Erase the element pointed to by pos.Precondition: The list is not empty.Postcondition: The list has one fewer element.

void erase(iterator first, iterator last);Erase all list elements within the iterator range [first,

last].Precondition: The list is not empty.Postcondition: The size of the list decreases by the

number of elements in the range.

Page 21: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 21

CLASS list Operations <list>

iterator insert(iterator pos, const T& value);Insert value before pos, and return an iterator pointing to the position of the new value in the list. The

operation does not affect any existing iterators.Postcondition: The list has a new element.

Page 22: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 22

Using Insert and Erase

int arr[5] = {9, 2, 7, 3, 12};list<int> lst(arr,arr+5);

list<int>::iterator listIter;

listIter = lst.end( );lst.insert(listIter, 14);listIter = lst.begin( );listIter = lst.insert(listIter, 55);lst.erase(listIter);

Page 23: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 23

CLASS list::iterator Operations <list>

* : Accesses the value of the item currently pointed to by the iterator.

*iter;*iter;

++ : Moves the iterator to the next item in the list. iter++;iter++;

-- : Moves the iterator to the previous item in the list.

iter--;iter--;

== : Takes two iterators as operands and returns true when they both point at the same item in the list.

iter1 == iter2iter1 == iter2

!= : Returns true when the two iterators do not point at the same item in the list.

iter1 != iter2iter1 != iter2

Page 24: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 24

Using Insert and Eraseint arr[5] = {9, 2, 7, 3, 12};list<int> lst(arr,arr+5);

list<int>::iterator listIter;

listIter = lst.begin( );listIter++;listIter++;cout << *listIter;lst.insert(listIter, 44);listIter--;lst.erase(listIter);

Page 25: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 25

Note about Iterators

List iterators move through the list in a circular fashion. When an iterator is at end(), the operation++ move the iterator to the first list element, at location begin();

Similarly, when an iterator is at begin(), the operation -- moves the iterator to end();

Page 26: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 26

iterator versus const_iterator Each standard library container (e.g. the list)

provides both aniterator

and aconst_iterator

The operations on them are the same, except When a const_iterator is dereferenced

(operator*), the value of the item referenced cannot be changed.

Page 27: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 27

Constant Iterators STL has a second type of iterator, constant

iterator. Much like regular iterator except you cannot

apply dereference (*) to a constant iterator on the left side of an assignment statement.

Cannot be used with list insert() and erase() Can use ++ and -- to move through list. Rule: use constant iterator to access and

scan a constant list.

list<T>::const_iterator iter;

Page 28: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 28

Iterator Hierarchy

Page 29: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 29

Iterator Functions

Function Behavior Required for Iterator Type const Item_Type& operator* Returns a reference to the object

referenced by the current iterator position that can be used on the right-hand side of an assignment.

All except output_iterator

Item_Type& operator* Returns a reference to the object referenced by the current iterator position that can be used on the left-hand side of an assignment.

All except input_iterator.

iterator& operator++() Prefix increment operator. All iterators. iterator operator++(int) Postfix increment operator All iterators iterator& operator--() Prefix decrement operator bidirectional_iterator and

random_access_iterator iterator operator--(int) Postfix decrement operator bidirectional_iterator and

random_access_iterator iterator& operator+=(int) Addition-assignment operator random_access_iterator iterator operator+(int) Addition operator random_access_iterator iterator& operator-=(int) Subtraction-assignment operator random_access_iterator iterator operator-(int) Subtraction operator random_access_iterator int operator-(random_access_iterator, random_access_iterator)

Subtraction of two iterators random_access_iterator

Page 30: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 30

TO ITERATE BACKWARDS, THERE IS

A DECREMENT OPERATOR. HERE IS

AN EXAMPLE:

list<double> roots;

for (int j = 0; j < 20; j++)roots.push_back (sqrt (j));

// Print sqrt (19), sqrt (18), …list<double>::iterator itr;for (itr = --roots.end( ); itr != --roots.begin( ); itr--)

cout << *itr << endl;

Page 31: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 31

BASICALLY, TO GET TO A POSITION

IN A list CONTAINER TAKES LINEAR-

IN-n TIME, BUT ONCE YOU GET

THERE, YOU CAN REMOVE OR

INSERT IN CONSTANT TIME.

Page 32: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 32

Inserting an element into a list

fro nt

Lis t o b je c t (a fte r)

fro nt re a r

Lis t o b je c t (b e fo re )

ne w E ltre a r

ite r

2 55937 2 9374

ite r4

list<int> intList (arr, arr+arrSize);list<int>::iterator iter, newElt;iter = intList.begin();iter++;newElt = intlist.insert ( iter, 4);

Page 33: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 33

Removing an element from a list

fro nt

Lis t o b je c t (a fte r)

fro nt re a r

Lis t o b je c t (b e fo re )

re a rite r

2 5937 2 593

ite r? ?

list<int> intList (arr, arr+arrSize);list<int>::iterator iter;iter = intList.begin();iter++;intlist.erase (iter);

Page 34: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 34

Ordered lists8 27 46 0

fro nt re a r6 5

8 27 46 0fro ntre a r

5 0 8 27 46 5

fro nt re a rc u rr

6 06 5

5 0

B e fo re Ins e rt A fte r Ins e rt

Position the iterator curr at the front of the list. Insert 50 in the list:

curr = intList.begin();

intList.insert (curr, 50);

Page 35: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 35

insertOrder()//insert item into the ordered list

template <typename T.

void insertOrder (list<t>& orderedList, const T& item)

{

// curr starts at first list element, stop marks end

list<T>::iterator curr = orderedList.begin(),

stop = orderList.end();

// find the insertion point

while ((curr != stop) && (*curr < item))

curr++;

// do the insertion using insert()

orderedList.insert (curr, item);

}

Page 36: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 36

EXERCISE: DETERMINE THE OUTPUT

FROM THE FOLLOWING PROGRAM

FRAGMENT:

Page 37: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 37

list<string>words; list<string>::iterator itr; string word; for (int i = 0; i < 5; i++) { word = (char)(i + 'a'); words.push_back (word); } // for // Now words contains ?? itr = words.begin( ); itr++; itr++; // itr positioned at ?? words.insert (itr, "true"); itr = words.insert (itr, "good"); words.insert (itr, "right"); for (itr = words.begin( ); itr != words.end( ); itr++) cout << *itr << endl;

Page 38: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 38

User’s Guide for choosing a list or vector If the application entails a lot of accessing

and/or modifying items at widely varying positions, a vector will be much faster than a list.

If a large part of the application consists of iterating through a container and making insertions and/or deletions during the iterations, a list will be much faster than a vector.

Page 39: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 39

THE list CLASS HAS SOME NEW

METHODS, SUCH AS

// Postcondition: The contents of x have been// inserted into the calling list object// in front of position, and x is now// empty.void splice (iterator position, list<T>& x);

RECALL THAT WHEN NO TIME

ESTIMATES ARE GIVEN, worstTime(n)

IS CONSTANT.

Page 40: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 40

FOR EXAMPLE, SUPPOSE THAT

names AND new_names ARE list

OBJECTS WITH string ITEMS:

names = “Mary”, “Joan”, “Paul”, “Marie”

new_names = “Don”, “Frank”

Page 41: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 41

IF itr IS POSITIONED AT “Paul”, AND

THE MESSAGE IS

names.splice (itr, new_names);

THEN names WILL CONSIST OF

“Mary”, “Joan”, “Don”, “Frank”, “Paul”, “Marie”

AND new_names WILL BE EMPTY.

Page 42: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 42

Splicing two lists

7 15 16 3 47 15 3 47 3 4

destList

15 16

sourceIter

sourceList pos

5

destList (After insert of 15)

15 16

sourceIter

sourceList pos

5

destList (After insert of 16)

sourceList pos

5

destList.splice(pos, sourceList);

Page 43: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 43

THERE ARE ALSO TWO VERSIONS

OF A sort METHOD. HERE IS THE

INTERFACE FOR SORTING ITEMS BY

operator<:

// Precondition: operator< is defined for the items.// Postcondition: The items in this list object are in// order by operator<. The// worstTime(n) is O(n log n).void sort( );

Page 44: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 44

FOR EXAMPLE, SUPPOSE THAT

names IS THE list CONTAINER

DESCRIBED EARLIER. IF THE

MESSAGE IS

names.sort( );

THEN names WILL CONSIST OF:

“Don”, “Frank”, “Joan”, “Marie”, “Mary, “Paul”

Page 45: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 45

THE FOLLOWING PROGRAM

FRAGMENT READS IN SEVERAL

WORDS, APPENDS THEM TO A list

CONTAINER, DELETES THE FIRST

AND LAST WORDS IN THE

CONTAINER, AND THEN PRINTS OUT

THE CONTAINER:

Page 46: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 46

list<string>words;

list<string>::iterator itr;

string word;

for (int i = 0; i < 5; i++) { cin >> word; words.push_back (word); } // for words.pop_front(); words.pop_back(); for (itr = words.begin(); itr != words.end(); itr++) cout << *itr << endl;

apple

banana

candy

donut

egg

Page 47: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 47

Linked List Basics

Node Composition Inserting at Front Deleting at Front Inserting in Middle Deleting from Middle

Page 48: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 48

Node Composition

n o de Va lue

n ext

n o d eValu e n ext

An individual Node is composed of two parts, a Data field containing the data stored by the node, and a Pointer field that marks the address of the next Node in the list.

Page 49: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 49

A List Node

A node contains: A data item One or more links

A link is a pointer to a list node The node class is usually defined inside another

class: It is a hidden inner class

The details of a node should be kept private

Page 50: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 50

List Nodes for Singly-Linked Lists

Page 51: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 51

Inserting at the Front of a Linked List fro n t

fro n t

B efo re

(a)

it em

n ew N o d e

A ft er

b ack

(b )

2 0

fro n t

B efo re

fro n t

5 5

2 0it em

fro n t

A ft er

fro n t

5 5

Page 52: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 52

Deleting From the Front of a Linked List

fro n t

fro n t

//

fro n t = N U L L

D elet in g fro n t o f a 1 -n o d e lis t

D elet in g fro n t o f a m u lt i-n o d e lis t

//

fro n t = fro n t -> n ext

Page 53: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 53

Removing a Target Node

ne xt

f ro nt

targe t

pre v c ur r

// //

Page 54: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 54

Doubly Linked Lists

Structure Inserting Circular doubly linked

Page 55: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 55

Doubly-Linked Lists

Limitations of a singly-linked list include: Can insert only after a referenced node Removing node requires pointer to previous

node Can traverse list only in the forward direction

We can remove these limitations: Add a pointer in each node to the previous node:

doubly-linked list

Page 56: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 56

Designing a New Linked List Structure

... //

i te m

ne wN o de

f ro nt

bac k

//

Page 57: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 57

Doubly-Linked Lists, The Diagrams

Page 58: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 58

Inserting a Node at a Position

ne xt pre v

pre vN ode = c urr -> pre v

p r ev item n ex t

143 2 c ur r

n ew N o d e

Page 59: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 59

Deleting a Node at a Position

pre v ne xt

s uc c N o de = c ur r->ne xt

1

2

//////

//

pre vN o de = c ur r->pre v c ur r

Page 60: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 60

Circular Doubly Linked Lists

A Watch Band provides a good Real Life analogue for this Data Structure

Firs t Ele m e n t

S e co n d Ele m e n t

L a s t Ele m e n t

Page 61: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 61

Circular Lists Circular doubly-linked list:

Link last node to the first node, and Link first node to the last

Advantages: Can easily keep going “past” ends Can visit all elements from any starting point Can never fall off the end of a list

Disadvantage: code must avoid infinite loop! Can also build singly-linked circular lists:

Traverse in forward direction only

Page 62: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 62

Circular Doubly Linked Lists

Implemented on a Computer it might look something like this.

head er

23 4 9

Page 63: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 63

Implementing a Circular List

Page 64: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 64

Updating a Doubly Linked List

p r e v n e x t

h ead er

B efo re In s ert : E m p t y lis t

p r e v n e x t

h ead er

n ew N o d e

A ft er Iin s ert : L is t w it h o n e elem en t

Page 65: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 65

struct versus class

A struct is the same as a class. Except that the default visibility for a struct is public.

Generally structs are used to define classes that only contain public data fields. Constructors may be provided. Other member functions (operators) are usually

not defined for structs.

Page 66: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 66

// Type DECLARATIONS

struct NodeType {char info;NodeType* prev;NodeType* next;

}

typedef NodeType* NodePtr;

// Variable DECLARATIONS

NodePtr head;NodePtr ptr;

Declarations for a Dynamic Linked List

.prev . info .

next

5000 ‘A’ 6000

Page 67: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 67

Pointer Dereferencing and Member Selection

. info . next

‘A’ 6000 ptr

ptr

ptr

. info . next

‘A’ 6000

*ptr

ptr

. info . next

(*ptr).info

ptr->info

‘A’ 6000

Page 68: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 68

ptr is a Pointer to a Node

. info . next

‘A’ 6000 ptr

ptr

Page 69: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 69

*ptr is the Entire Node Pointed to by ptr

ptr

. info . next

‘A’ 6000

*ptr

Page 70: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 70

ptr->info Is a Node Member

ptr

. info . next

ptr->info

(*ptr).info // equivalent

‘A’ 6000

Page 71: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 71

ptr->link Is a Node Member

ptr

. info . next

ptr->next

(*ptr).next // equivalent

‘A’ 6000

Page 72: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 72

Inserting a Node into a Single Linked ListNode* bob = new Node("Bob");bob->next = harry->next; // step 1harry->next = bob; // step 2

Page 73: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 73

Removing a node from a single-linked list

Node* ptr = tom->next;tom->next = tom->next->next;delete ptr;

Page 74: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 74

Inserting into a Double-Linked List

DNode* sharon = new DNode("Sharon");// Link new DNode to its neighborssharon->next = sam; // Step 1sharon->prev = sam->prev; // Step 2

Page 75: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 75

Inserting into a Double-Linked List (2)

// Link old predicessor of sam to new predicessor.sam->prev->next = sharon; // Step 3// Link to new predicessor.sam->prev = sharon; // Step 4

Page 76: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 76

Removal from a Double-Linked List

harry->prev->next = harry->next; // Step 1harry->next->prev = harry->prev; // Step 2delete harry;

Page 77: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 77

FIELDS AND IMPLEMENTATION OF

THE list CLASS (HEWLETT-PACKARD)

Page 78: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 78

THERE IS A STRUCT: struct list_node { list_node* next; list_node* prev; T data; // holds one item }; // list_node

Page 79: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 79

HERE IS THE BASIC ORGANIZATION:

prev data next prev data next

IN EACH list_node, THE data FIELD

HOLDS THE ITEM, prev POINTS TO

THE PREVIOUS list_node, AND next

POINTS TO THE NEXT list_node.

Page 80: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 80

HERE ARE TWO OF THE FIELDS:

protected:unsigned length;

list_node* node;

THE node FIELD POINTS TO A

DUMMY list_node, WHICH IS

CALLED THE “HEADER NODE”.

Page 81: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 81

IN THE HEADER NODE, THE data

FIELD IS UNUSED. THE DEFAULT

CONSTRUCTOR MAKES THE prev

AND next FIELDS OF THE HEADER

NODE POINT BACK TO THE HEADER

NODE ITSELF: (*node).next = node; // node->next = node; (*node).prev = node; // node->prev = node;

Page 82: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 82

AN EMPTY LIST:

length

node prev data next

0

/** Construct an empty list. */list() { node = new list_node(); node->next = node; node->prev = node; length = 0;}

Page 83: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 83

IN A NON-EMPTY LIST, THE HEADER

NODE’S next FIELD POINTS TO THE

NODE THAT CONTAINS THE FRONT

ITEM, AND THE HEADER NODE’S

prev FIELD POINTS TO THE NODE

THAT CONTAINS THE BACK ITEM.

Page 84: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 84

A LIST WITH ONE ITEM:

length

node

1

Al

Page 85: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 85

A LIST WITH TWO ITEMS:

length

node

2

Al Bo

Page 86: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 86

THE REPRESENTATION OF A LIST IS

CIRCULAR: THE list_node FOLLOWING

THE LAST NODE IS THE HEADER

NODE, AND THE list_node FOLLOWING

THE HEADER NODE IS THE FIRST

NODE.

Page 87: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 87

THE HEADER NODE SIMPLIFIES THE

DEFINITION OF SEVERAL METHODS

BECAUSE FOR ANY LIST NODE, EVEN

THE FIRST OR LAST, THERE IS A LIST

NODE IN FRONT OF IT AND A LIST

NODE IN BACK OF IT.

Page 88: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 88

BECAUSE THE insert AND erase

METHODS HAVE AN ITERATOR

PARAMETER, WE NEED TO LOOK AT

THE FIELDS AND IMPLEMENTATION

OF THE iterator CLASS EMBEDDED IN

THE list CLASS.

Page 89: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 89

THE iterator CLASS HAS ONE FIELD

AND A CONSTRUCTOR TO INITIALIZE

THAT FIELD:

protected: list_node* node;

iterator (list_node* x) : node (x) { }

THE CONSTRUCTOR INITIALIZER

SECTION INITIALIZES node TO x.

Page 90: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 90

THE DEFINITIONS OF THE OTHER

iterator METHODS ARE

STRAIGHTFORWARD. FOR EXAMPLE,

HERE IS THE DEFINITION OF THE

PRE-DECREMENT OPERATOR: iterator& operator-- ( ) { node = (*node).prev; return *this; }

Page 91: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 91

IMPORTANT!

THE INSERTION IS MADE

WITHOUT MOVING ANY

ITEMS ALREADY IN THE

LIST. THE worstTime(n) IS

CONSTANT.

Page 92: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 92

Linked Lists in Arrays

Begin with a large workspace array and regard the array as our allocation of unused space.

Set up functions to keep track of which parts of the array are unused and to link entries of the array together in the desired order.

The one feature of linked lists that you invariably lose in this implementation method is the dynamic allocation of storage.

Page 93: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 93

Linked Lists in Arrays

Applications where linked lists in arrays may prove preferable are those where: The number of entries in a list is known in

advance, The links are frequently rearranged, but relatively

few additions or deletions are made, or The same data are sometimes best treated as a

linked list and other times as a contiguous list.

Page 94: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 94

Example

Page 95: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 95

Page 96: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 96

Implementations

What are the data members? What is the logic for insert and delete? How would you keep track of the iterator?

Page 97: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 97

Set Position How would you implement the following:

Singly linked Doubly linked Array based implementation

template <typename List_entry>Node<List_entry> *List<List_entry>::set_position

(int position) const;// Pre: position is a valid position in the List; 0 <=

position < count// Post: Returns a pointer to the Node in position

Page 98: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 98

Insert Function

template <typename List_entry>

void List<List_entry>::insert ( int position, const List_entry &x);

Page 99: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 99 99

Summary Slide 1§- list

- A Sequence of elements stored by position.

- Index access is not available…§- to access the value of an element, must pass

through its preceding elements.

§- list iterator- A generalized pointer that moves through a list

element by element… forward or backward

- At any point, the * operator accesses the value of a list item.

Page 100: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 100 100

Summary Slide 2§- The list class has two iterator types:

1)1) iteratoriterator:

A generalized list traversal pointer.

2)2) constconst __ iteratoriterator:

must be used with a constant list object. Each type is a nested class of list and must be

accessed by using the scope operator ::::

Page 101: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 101 101

Summary Slide 3§- the list member function begin()

- Gives an iterator an initial value that points to the first element.

§- the list member function end()- Returns an iterator pointing just past the last

element of the list.

Page 102: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 102 102

Summary Slide 4§- The sequential search of a list object

- implemented by using an iterator range [firstfirst, lastlast).

- It returns an iterator that points at the target value or has value lastlast if the target is not in the list.

Page 103: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 103 103

Summary Slide 5§- list class member fns insert() and

erase() - Both use an iterator argument to modify a list.

1)1) insert()insert(): places value in the list before the data

referenced by the iterator pospos.

2)2) erase()erase():removes the data item referenced by pospos from the list.

Page 104: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 104 104

Summary Slide 6§- singly linked lists

- Each node contains a value and a pointer to the next node in the list.

- The list begins with a pointer to the first node of the list and terminates when a node has a NULL pointer.

Page 105: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 105 105

Summary Slide 7§- Inserting/Deleting at the front of a singly

linked list1)Insert

- Set the pointer in the new node to the previous value of front.

- update front to point at the new node.

2)Erase

- assign front the pointer value of the first node, and then delete the node.

Page 106: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 106 106

Summary Slide 8§- Inserting/Erasing inside a singly linked

list- Maintain a pointer to the current list node and a

pointer to the previous node.

- Change the pointer value in the previous node.

Page 107: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 107 107

Summary Slide 9§- Insert/Delete at the back of a singly

linked list- Maintain a pointer to the last list node that has

value NULL when the list is empty.

- Assign a “back” pointer the address of the first node added to the list.

- To add other nodes at the back:1) allocate a new node

2) assign the pointer in node “back” to point to the new node

3) assign the pointer “back” the address of the new node.

Page 108: Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

Lists 108 108

Summary Slide 10§- Doubly linked lists

- provide the most flexible implementation for the sequential list.

§- Its nodes have pointers to the next and the previous node, so the program can traverse a list in either the forward or backward direction.

- Traverse a list by starting at the first node and follow the sequence of next nodes until you

arrive back at the header.- To traverse a list in reverse order, start at the last

node and follow the sequence of previous nodes until arriving back at the header.