Transcript Lecture 2

Brief Review of ADTs and
Class Implementation
Chapter 4-8
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
1
Contents
1.
2.
3.
4.
ADT? (ch. 2)
Classes (ch. 4)
List and its class implementation (ch. 6)
Stack and its class implementation (ch.
7)
5. Queue and its class implementation (ch.
8)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
2
Objectives
•
•
•
•
•
Review ADTs
Review classes in C++
Review list with class implementation
Review stack with class implementation
Review Queue with class implementation
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
3
What is ADT?
• ADT = data items + operations on the data
• Implementation of ADT
– Storage/data structures to store the data
– Algorithms for the operations, i.e., how to do it
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
4
Structs and Classes
Similarities
• Essentially the same syntax
• Both are used to model objects with multiple
attributes (characteristics)
– represented as data members
– also called fields … or …
– instance or attribute variables
• Thus, both are used to process nonhomogeneous data sets.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
5
Structs vs. Classes
Differences
• No classes in C
• Members public by
default
• Can be specified
private
• Both structs and
classes in C++
• Structs can have
members declared
private
• Class members are
private by default
• Can be specified public
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
6
Advantages in C++
(structs and Classes)
• C++ structs and classes model objects
which have:
– Attributes represented as data members
– Operations represented as functions (or
methods)
• Leads to object oriented programming
– Objects are self contained
– "I can do it myself" mentality
– They do not pass a parameter to an external
function
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
7
Class Declaration
• Syntax
class ClassName
{
public:
Declarations of public members
private:
Declarations of private members
};
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
8
Designing a Class
• Data members normally placed in private:
section of a class (information hiding)
• Function members usually in public: section
(exported for external use)
• Typically public: section followed by private:
– although not required by compiler
– Actually nobody cares, at least for me
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
9
Class Libraries
• Class declarations placed in header file
– Given .h extension
– Contains data items and prototypes
• Implementation file
– Same prefix name as header file
– Given .cpp extension
• Programs which use this class library called
client programs
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
10
Translating a Library
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
11
Example of User-Defined
Time Class
• Now we create a Time class (page 150)
– Actions done to Time object, done by the object itself
• Note interface for Time class object,
Fig. 4.2
– Data members private – inaccessible to users of the
class
– Information hiding
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
12
Constructors
• Understanding Constructors, p158-159
– Initialize data members
– Optional: allocate memory
• Note constructor definition in Time.cpp
example (p161)
• Syntax
ClassName::ClassName (parameter_list)
: member_initializer_list
{
// body of constructor definition
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
13
Constructors
• Results of default constructor
• Results of explicit-value
constructor
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
14
Overloading Functions
• Note existence of multiple functions with the
same name
Time();
Time(unsigned initHours,
unsigned initMinutes,
char initAMPM);
– Known as overloading
• Compiler compares numbers and types of
arguments of overloaded functions
– Checks the "signature" of the functions
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
15
Default Arguments
• Possible to specify default values for
constructor arguments
Time(unsigned initHours = 12,
unsigned initMinutes = 0,
char initAMPM = 'A');
• Consider
Time t1, t2(5), t3(6,30), t4(8,15,'P');
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
16
Copy Operations(p166)
• During initialization
Time t = bedTime
• During Assignment
t = midnight;
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
17
Overloading Operators
• Same symbol can be used more than one
way
• Operator , function: operator ()
• Two cases
– If  is a function member:
a b  a.operator (b)
– Otherwise, a b  operator (a,b)
• Operators: +,-,*,/
• Operators: <<, >>
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
18
Overloading <<
• void operator<<(ostream& out, const Time&
t)
• ostream& operator<<(ostream& out, const
Time& t)
• Question: which one is right? Why?
• See p170-171
• See example p173: why need a member
function to overload << and >>?
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
19
Friend Functions
• Note use of two functions used for output
– display() and operator<<()
• Possible to specify operator<<() as a "friend"
function
– Thus given "permission" to access private data
elements
• Declaration in .h file (inside the class
declaration with friend keyword)
friend ostream & operator<<(
ostream & out, const Time & t)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
20
Friend Functions
• Definition in .cpp file
ostream & operator<<(
ostream & out, const Time & t)
{ out << t.myHours<<":"
<<(t.myMinutes< 10? •"0":
Author "")
prefers not to use
<<t.myMinutes
friend function
<< ' '<<t.myAMorPM<<".M.";
• Violates principle of
return out;
information hiding
}
• Note - a friend function not member function
– not qualified with class name and ::
– receives class object on which it operates as a
parameter
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
21
Other Operations
• Advance Operation
– Time object receives a number of hours and
minutes
– Advances itself by adding to myHours,
myMinutes
• Relational Operators
– Time object compares itself with another
– Determines if it is less than the other
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
22
Redundant Declarations
• Note use of #include "Time.h" in
– Time.cpp
– Client program
• Causes "redeclaration" errors at compile time
• Solution is to use conditional compilation
– Use #ifndef and #define and #endif compiler
directives
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
23
Pointers to Class Objects
• Possible to declare pointers to class objects
Time * timePtr = &t;
• Access with
timePtr->getMilTime() or
(*timePtr).getMilTime()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
24
The this Pointer
• Every class has a keyword, this
– a pointer whose value is the address of the
object
– Value of *this would be the object itself
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
25
Exercises
• Implement a polynomial class in the form of
ax+b, coefficients a and b are integers.
– Constructor
– Overload operator+
– Overload operator<<, do not use friend function.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
26
Review for Last Class’s Example
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
27
Example for class “ax+b”
//poly.h: header file
#include <iostream>
#ifndef _POLY_H // avoid redundant declarations
#define _POLY_H
class Poly {
private:
int m_ca; //coefficient a
int m_cb;
public:
Poly(int a, int b) : m_ca(a), m_cb(b) { }; //constructor
void display(ostream& out) const; //for operator << overloading
Poly operator+(const Poly& po); //overloading +
}; //do not forget to put ; !!!!
ostream& operator<<(ostream& out, const Poly& po); //overloading <<
#endif
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
28
Example: ax+b
//poly.cpp: implementation file
#include “poly.h”
using namespace std;
void Poly::display(ostream& out) const {
out << m_ca << “x + ” << m_cb << endl;
}
Poly Poly::operator+(const Poly& po) {
Poly c;
c.m_ca = this->m_ca + po.m_ca; //what is “this”? Do we need it here?
c.m_cb = m_cb + po.m_cb;
return c;
}
ostream& operator<<(ostream& out, const Poly& po) {
po.display(out);
return out;
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
29
To-do-list
• Review: class, overloading operators
• In-class Exercise
– Operator “-” and “>>” overloading in last class
example
• List implementations
– Destructor
– Copy constructor
– Assignment operator
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
30
Lists
Chapter 6
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
31
Chapter Contents
6.1 List as an ADT
6.2 An Array-Based Implementation of Lists
6.3 An array Based Implementation of Lists
with Dynamic Allocation
6.4 Introduction to Linked Lists
6.5 A Pointer-Based Implementation of Linked
Lists in C++
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
32
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
33
Consider Every Day Lists
•
•
•
•
Groceries to be purchased
Job to-do list
List of assignments for a course
Dean's list
• Can you name some others??
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
34
Properties of Lists
• Can have a single element
• Can have no elements  empty!
• There can be lists of lists
• We will look at the list as an abstract data
type
– Homogeneous
– Finite length
– Sequential elements
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
35
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
36
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
37
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
38
Implementing Operations
• Constructor
– Static array allocated at compile time. No need to allocate explicitly!
• Empty
– Check if size == 0
– Traverse
– Use a loop from 0th element to size – 1
• Insert
– Shift elements to
right of insertion point
• Delete
– Shift elements back
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
Also adjust
size up or
down
39
List Class with Static Array
• Must deal with issue of declaration of
CAPACITY, p262
• Use typedef mechanism
typedef Some_Specific_Type ElementType
ElementType array[CAPACITY];
• For specific implementation of our class we
simply fill in desired type for
Some_Specific_Type
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
40
List Class with Static Array
• Can put typedef declaration inside or
outside of class
– Inside: must specify List::ElementType
for reference to the type outside the class
– Outside: now able to use the template
mechanism (this will be our choice)
• Also specify the CAPACITY as a const
– Also choose to declare outside class
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
41
List Class Example, p262
• Declaration file, Fig. 6.1A
– Note use of typedef mechanism outside the
class
– This example good for a list of int
• Definition, implementation Fig. 6.1B
– Note considerable steps required for insert()
and erase() functions
• Program to test the class, Fig 6.1C
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
42
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
43
Dynamic-Allocation for List Class
• Changes required in data members
– Eliminate const declaration for CAPACITY
– Add 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()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
44
Dynamic-Allocation for List Class
• Note data changes in Fig. 6.2A, List.h,p270
• Note implementation file Fig. 6.2B, List.cpp
– Changes to constructor
– Addition of other functions to deal with
dynamically allocated memory
• Note testing of various features in Fig. 6.2C,
the demo program
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
45
Dynamic-Allocation for List Class
• Now possible to specify different sized lists
cin >> maxListSize;
List aList1 (maxListSize);
List aList2 (500);
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
46
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
47
New Functions Needed
• Copy Constructor – makes a "deep copy" of
an object, p278
– 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)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
48
Copy Constructor, p280
• The parameter must be a reference parameter and
should be a const reference parameter as well
– If value parameter, infinite chain of function calls!!!
– List(const List& org)
• Work to be done
– Allocate memory
– Ensure deep copy by element-by-element copy
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
49
New Functions Needed
• Assignment operator
– Default assignment operator makes shallow
copy
– Can cause memory leak, previous dynamicallyallocated memory has nothing pointing to it
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
50
Assignment Operator
• Must be member function, a=b 
a.operator=(b)
• Return const reference to the object
– const ClassName& operator=(const ClassName& right)
• First check if self-assignment: otherwise
having problem in “list1 = list1”;
• Avoid memory leak by releasing previous
allocated memory
• Ensure deep copy
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
51
Difference between Copy constructor and Assignment Operator
•
•
•
•
Function return value?
Self assignment check?
Memory leak?
Deep copy?
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
52
Notes on Class Design
If a class allocates memory at run time using
the new, then a it should provide …
• A destructor
• A copy constructor (by complier to make a
copy)
• An assignment operator (by programmer)
• Note Fig. 6.3 which exercises constructors
and destructor, p263
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
53
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
time
Solution:
– Create multiple List classes with differing
names
– Use class template
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
54
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
55
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 location.
2. But then need a "link" that connects each element
to its successor
Linked Lists !!
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
56
Linked List
• Linked list nodes contain
– Data part – stores an element of the list
– Next part – stores link/pointer to next element
(when no next element, null value)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
57
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
58
Linked Lists Operations
• Traverse (ctd)
– set ptr
= ptr->next, process ptr->data
– Continue until ptr == null
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
59
Operations: Insertion
predptr
• Insertion
20
newptr
– 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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
60
Operations: Insertion
• Note: 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
 Note: In all cases, no shifting of list
elements is required !
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
61
Operations: Deletion
predptr
ptr
• Delete node containing 22 from list.
To free
space
– 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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
62
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
63
Linked Lists - Disadvantages
• Overhead of links:
– used only internally, pure overhead
• If dynamic, must provide
– destructor
– copy constructor
• 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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
64
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
65
Using C++ Pointers and Classes
• To Implement Nodes
class Node
{
public:
DataType 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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
66
Working with Nodes
• Declaring pointers
Node * ptr;
or
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
or
ptr->data
and
ptr->next
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
67
Working with Nodes
• Note data members
are public
class Node
{
public:
DataType data;
Node * next;
};
• This class declaration will be placed inside
another class declaration for List
(private section), p296
• The data members data and next of
struct Node will be public inside the class
– will accessible to the member and friend
functions of List
– will be private outside the class
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
68
Class List
typedef int ElementType;
class List
{
• data is public inside
private:
class Node
class Node
{
• class Node is private
public:
inside List
ElementType data;
Node * next;
};
typedef Node * NodePointer;
. . .
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
69
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
70
Function Members for Linked-List
Implementation
• Constructor
– Make first a null pointer and
– set mySize to 0
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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
71
Function Members for Linked-List
Implementation
Shallow Copy
• 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
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
72