List - Help-A-Bull

Download Report

Transcript List - Help-A-Bull

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
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
2
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
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
List Class with Static Array (Review)
Use template
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[CAPACITY]; // array to store list elements
int _size; // current size of the list stored in _items
};
5
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 dynamicallyallocated array
6
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
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
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 array
Nyhoff, ADTs, Data Structures and Problem Solving with
C++, Second Edition, © 2005 Pearson Education, Inc. All
rights reserved. 0-13-140909-3
9
http://www.american-buddha.com/GHOST.253.htm
http://www.screeninsults.com/ghostbusters.php
Nyhoff, ADTs, Data Structures and Problem Solving with
C++, Second Edition, © 2005 Pearson Education, Inc. All
rights reserved. 0-13-140909-3
10
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
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
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
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 point
to new node.
14
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
Array-Based Implementation of Linked
Lists
• Given a list with names
• Implementation would
look like this
16
Chapter Contents
11.1 Some Variants of Singly-Linked Lists
11.2 Linked Implementation of Sparse Polynomials
11.3 Doubly-Linked Lists and the Standard C++ list
11.4 Case Study: Larger-Integer Arithmetic
11.5 Other Multiply-Linked Lists
17
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
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
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
Linked Lists with Head Nodes
• For insertion at beginning of list
• Head node is predecessor for new node
newptr->next = predptr->next;
predptr->next = newptr;
21
Linked Lists with Head Nodes
• For deleting first element from a list with a head node
• Head node is the predecessor
predptr->next = ptr->next;
delete ptr;
22
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
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
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
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
Doubly-Linked Lists
• To delete a node
• Reset forward link of predecessor, backward link of successor
• Then delete removed node
27
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
Comparing List<t> With Other Containers
Property
Array
vector<T> deque<T> list<T>
Direct/random access ([]) Excellent
Excellent
Good
Sequential access
Excellent
Good
Excellent
Excellent
Excellent
Excellent
Excellent
Insert/delete at front
Insert/delete at end
Insert/delete in middle
Overhead
Excellent
Poor
Excellent
Poor
Excellent
Poor
Poor
lowest
low
Poor
NA
Excellent
low/medium
high
• Note : list<T> does not support direct access
• does not have the subscript operator [
]
29
list<t> Iterators
• list<T>'s iterator is "weaker" than that for
vector<T>
 vector<T>:

list<T>:
random access iterators
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
list<t> Iterators
• Operators in common
 = assignment
(for same type iterators)
it1 = it2 makes it1 positioned at
element as it2
 == and !=
(for same type iterators)
checks whether iterators are positioned at
same
the same element
See basic list operations,
Table 11-2
View demonstration of list operations, Fig. 11-1
31
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
The STL list<T> Class Template
Node structure
struct list_node
{
pointer next,
prev;
T data;
}
33
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
The STL list<T> Memory Management
When a node is allocated
1.
If there is a node on the free list, allocate it.
•
2.
This is maintained as a linked stack
If the free list is empty:
a)
b)
Call the heap manager to allocate a block of memory (a "buffer", typically 4K)
Carve it up into pieces of size required for a node of a list<T>
35
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
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
Multiply-Ordered Lists
• Better approach
• Single list
• Multiple links
38
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
Sparse Matrices
A=
• For
we represent with
40
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
A=
41
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
A=
42
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
Sparse Matrices
• Note the resulting
representation of
the matrix
A=
44
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
This is an
example of a
generalized list
45
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
Generalized Lists
• Lists can be
shared
• To represent
(2, (4,6), (4,6))
• For polynomials in two variables
P(x,y) = 3 + 7x + 14y2 + 25y7 – 9x2y7 + 18x6y7
• P(x,y) = (3 + 7x) + 14y2 + (25 – 9x2 + 18x6)y7
47