47
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++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1

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++,

Embed Size (px)

Citation preview

Page 1: 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++,

More Linking Up with Linked Lists

Chapter 115/19/2015

Adopted from instructor resource 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: 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++,

2

Lists (Review)• Properties of a list:

• Homogeneous• Finite length• Sequential elements

• Basic Operations for a List Class:• Constructor• empty()• insert()• delete()• display()

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

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

rights reserved. 0-13-140909-3

Page 3: 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++,

Using a Template? (Review)

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

• Allows for flexibility/versatility

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

Page 4: 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++,

Array-Based Implementation of Lists (Review)

• 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

4

Page 5: 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++,

List Class with Static Array (Review)

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

};5

Page 6: 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++,

List Class with Static Array – Problems (Review)• 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

6

Page 7: 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++,

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()

7

Page 8: 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++,

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

};

8

Page 9: 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++,

9

New Functions Needed (Review)• “Rule of 3” if need one, probably need all 3 of these functions• 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

• Copy Constructor• 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

• 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 arrayNyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All

rights reserved. 0-13-140909-3

Page 10: 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++,

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

rights reserved. 0-13-140909-3

http://www.screeninsults.com/ghostbusters.php

http://www.american-buddha.com/GHOST.253.htm

Page 11: 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++,

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)

11

Page 12: 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++,

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

12

Page 13: 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++,

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.

13

Page 14: 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++,

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

14

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 15: 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++,

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

15

Page 16: 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++,

Array-Based Implementation of Linked Lists

• Given a list with names

• Implementation wouldlook like this

16

Page 17: 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++,

Chapter Contents

11.1 Some Variants of Singly-Linked Lists11.2 Linked Implementation of Sparse Polynomials11.3 Doubly-Linked Lists and the Standard C++ list11.4 Case Study: Larger-Integer Arithmetic11.5 Other Multiply-Linked Lists

17

Page 18: 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++,

Chapter Objectives

• Survey common variants of linked lists and why they are used

• Describe doubly-linked lists and how they are used to implement C++ STL list container

• Look briefly at some other applications of multiply-linked lists

18

Page 19: 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++,

Linked Lists with Head Nodes

• Consider linked lists from Chapter 6• First node is different from others• Has no predecessor

• Thus insertions and deletions must consider two cases• First node or not first node• The algorithm is different for each

19

Page 20: 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++,

Linked Lists with Head Nodes

• Dual algorithms can be reduced to one• Create a "dummy" head node• Serves as predecessor holding actual first element

• Thus even an empty list has a head node

20

Page 21: 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++,

Linked Lists with Head Nodes

• For insertion at beginning of list• Head node is predecessor for new nodenewptr->next = predptr->next;predptr->next = newptr;

21

Page 22: 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++,

Linked Lists with Head Nodes

• For deleting first element from a list with a head node• Head node is the predecessorpredptr->next = ptr->next;delete ptr;

22

Page 23: 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++,

Circular Linked Lists• Set the link in last node to point to first node

• Each node now has both predecessor and successor• Insertions, deletions now easier

• Special consideration required for insertion to empty list, deletion from single item list

23

Page 24: 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++,

Circular Linked Lists

• Traversal algorithm must be adjusted(first != 0) // list not empty{

ptr = first;do { // process ptr->data

ptr = ptr->next; } while (ptr != first);

}

• A do-while loop must be used instead of a while loop

• Why is this required?

24

Page 25: 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++,

Doubly-Linked Lists

• Bidirectional lists• Nodes have data part,

forward and backward link

• Facilitates both forward and backward traversal• Requires pointers to both first and last nodes

25

Page 26: 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++,

Doubly-Linked Lists• To insert a new node

• Set forward and backward links to point to predecessor and successor

• Then reset forward link of predecessor, backward link of successor

26

Page 27: 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++,

Doubly-Linked Lists

• To delete a node• Reset forward link of predecessor, backward link of successor• Then delete removed node

27

Page 28: 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++,

The STL list<T> Class Template• A sequential container

• Optimized for insertion and erasure at arbitrary points in the sequence.• Implemented as a circular doubly-linked list with head node.

28

Page 29: 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++,

Comparing List<t> With Other Containers

• Note : list<T> does not support direct access • does not have the subscript operator [ ]

29

Property Array vector<T> deque<T> list<T>

Direct/random access ([]) Excellent Excellent Good NASequential access Excellent Excellent Good ExcellentInsert/delete at front Poor Poor Excellent Excellent

Insert/delete in middle Poor Poor Poor Excellent

Insert/delete at end Excellent Excellent Excellent Excellent

Overhead lowest low low/mediumhigh

Page 30: 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++,

list<t> Iterators•list<T>'s iterator is "weaker" than that for vector<T>

vector<T>: random access iterators list<T>: bidirectional iterators

• Operations in common++ Move iterator to next element

(like ptr = ptr-> next) -- Move iterator to preceding element

(like ptr = ptr-> prev)* dereferencing operator

(like ptr-> data)

30

Page 31: 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++,

list<t> Iterators• Operators in common

= assignment (for same type iterators) it1 = it2 makes it1 positioned at same element as it2

== and != (for same type iterators) checks whether iterators are positioned at the

same element

See basic list operations, Table 11-2

View demonstration of list operations, Fig. 11-1

31

Page 32: 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++,

Example: Internet Addresses

• Consider a program that stores IP addresses of users who make a connection with a certain computer

• We store the connections in an AddressCounter object• Tracks unique IP addresses and how many times that IP connected

• View source code, Fig. 11.2• Note uses of STL list and operators

32

Page 33: 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++,

The STL list<T> Class TemplateNode structure

struct list_node

{ pointer next, prev;T data; }

33

Page 34: 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++,

The STL list<T> Class Template• But it's allo/deallo-cation scheme is complex

• Does not simply using new and delete operations.

• Using the heap manager is inefficient for large numbers of allo/deallo-cations

• Thus it does it's own memory management.

34

Page 35: 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++,

The STL list<T> Memory Management

When a node is allocated1. If there is a node on the free list, allocate it.

• This is maintained as a linked stack

2. If the free list is empty:a) Call the heap manager to allocate a block of memory (a "buffer", typically 4K)b) Carve it up into pieces of size required for a node of a list<T>

35

Page 36: 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++,

The STL list<T> Memory Management

• When a node is deallocated• Push it onto the free list.

• When all lists of this type T have been destroyed• Return it to the heap

36

Page 37: 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++,

Multiply-Ordered Lists

• Ordered linked list• Nodes arranged so data items are in ascending/descending order

• Straightforward when based on one data field• However, sometimes necessary to maintain links with a different ordering

• Possible solution• Separate ordered linked lists – but wastes space

37

Page 38: 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++,

Multiply-Ordered Lists

• Better approach• Single list• Multiple links

38

Page 39: 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++,

Sparse Matrices• Usual storage is 2D array or 2D vector• If only a few nonzero entries

• Can waste space

• Stored more efficiently with linked structure• Similar to sparse polynomials• Each row is a linked list• Store only nonzero entries for the row

39

Page 40: 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++,

Sparse Matrices

• For

we represent with

40

A =

Page 41: 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++,

Sparse Matrices

• This still may waste space• Consider if many rows were all zeros

• Alternative implementation• Single linked list• Each node has row, column,

entry, link

• Resulting list

41

A =

Page 42: 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++,

Sparse Matrices

• However … this loses direct access to rows• Could replace array of pointers with

• Linked list of row head nodes• Each contains pointer to non empty row list

42

A =

Page 43: 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++,

Sparse Matrices

• If columnwise processing is desired• Use orthogonal list• Each node stores row, column, value, pointer to row successor, pointer to

column successor• Each row list and column list is a circular list with a head node

• These head nodes are linked together to form another circular list with a “master” head node

43

Page 44: 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++,

Sparse Matrices• Note the resulting

representation of the matrix

44

A =

Page 45: 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++,

Generalized Lists

• Examples so far have had atomic elements• The nodes are not themselves lists

• Generalized List: a list where the elements themselves are lists• Consider a linked list of strings

• The strings themselves can be linked lists of characters

45

This is an example of a

generalized list

This is an example of a

generalized list

Page 46: 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++,

Generalized Lists

• Commonly represented as linked lists where• Nodes have a tag field along with data and link

• Tag used to indicate whether data field holds• Atom• Pointer

to a list

46

Page 47: 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++,

Generalized Lists

• Lists can be shared

• To represent (2, (4,6), (4,6))

• For polynomials in two variablesP(x,y) = 3 + 7x + 14y2 + 25y7 – 9x2y7 + 18x6y7

• P(x,y) = (3 + 7x) + 14y2 + (25 – 9x2 + 18x6)y7

47