Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

List Definitions

Linear relationship Each element except


the first has a unique predecessor, and
each element except the last has a
unique successor.
Length The number of items in a list; the
length can vary over time.
3
ADT Unsorted List

1 2

List Definitions Abstract Data Type (ADT)

Unsorted list A list in which data items are


placed in no particular order; the only
relationship between data elements is the list • A data type whose properties (domain
predecessor and successor relationships. and operations) are specified
Sorted list A list that is sorted by the value in independently of any particular
the key; there is a semantic relationship implementation.
among the keys of the items in the list.
Key The attributes that are used to determine
the logical order of the list.

3 4
Data from 3 different levels
Remember ???
• Application (or user) level: modeling real-life • Constructor
data in a specific context.

• Logical (or ADT) level: abstract view of the • Transformer


domain and operations.

• Implementation level: specific representation


of the structure to hold the data items, and
• Observer
the coding for operations.
• Iterator

5 6

Sorted and Unsorted Lists ADT Unsorted List Operations


Transformers
• MakeEmpty
UNSORTED LIST SORTED LIST change state
• PutItem
Elements are placed List elements are in an • DeleteItem
into the list in order that is sorted in Observers
no particular order. some way -- either
numerically or • IsFull
• GetLength observe state
alphabetically by the
elements themselves, or
• GetItem
by a component of the
element (called a KEY
member) .
Iterators
• ResetList process all
• GetNextItem
7 8
What is a Generic Data Type? Specification of ItemType
Structure: The list elements are of ItemType.
Definitions and Operation (provided by user):
A generic data type is a type for which the
MAX_ITEMS A constant specifying the maximum number of items on the
operations are defined but the types of the list.
items being manipulated are not defined. ItemType Class encapsulating the type of the items in the list.
RelationType An enumeration type that consists of LESS, GREATER,
EQUAL.
One way to simulate such a type for our Member function of ItemType that must be included:
UnsortedList ADT is via a user-defined class RelationType ComparedTo(ItemType item)
ItemType with member function Function Determines the ordering of two ItemType objects based on
their keys.
ComparedTo returning an enumerated type
Precondition
value LESS, GREATER, or EQUAL. Postcondition Returns LESS if the key of self is less than the key of item,
GREATER if the key of self is greater than the key of item
and
9 10 EQUAL if the keys are equal.

ItemType Class Interface Diagram Specifying class ItemType


// SPECIFICATION FILE ( ItemType.h )
class ItemType #include <iostream>
Using namespace std;

ComparedTo const int MAX_ITEM = 5 ;


enum RelationType { LESS, EQUAL, GREATER };

Private data class ItemType // declares class data type


Print {
value public : // 3 public member functions
RelationType ComparedTo ( ItemType ) const;
void Print ( ofstream& ) const;
Initialize void Initialize ( int ) ;

private : // 1 private data member


int value ; // could be any different
// type, including a class
11
} ; 12
// IMPLEMENTATION FILE ( ItemType.cpp )
// Implementation depends on the data type of value.

#include “ItemType.h”
Class Constructor
RelationType ItemType::ComparedTo(ItemType otherItem)
const
{ A special member function of a class
if ( value < otherItem.value )
return LESS; that is implicitly invoked when a class
else if ( value > otherItem.value )
return GREATER; object is defined.
else return EQUAL;
}
void ItemType::Print ( ofstream& out) const
{
out << value << endl;
}
void ItemType::Initialize ( int number )
{
value = number;
}

13 14

Class Constructor Rules Class Interface Diagram

1 A constructor cannot return a function value, and UnsortedType class


has no return value type. UnsortedType
2 A class may have several constructors. The Private data:
IsFull
compiler chooses the appropriate constructor by the
length
number and types of parameters used. GetLength
3 Constructor parameters are placed in a parameter info [0]
GetItem [1]
list in the declaration of the class object. [2]
PutItem
4 The parameterless constructor is the default
[MAX_ITEMS-1]
constructor. DeleteItem

5 If a class has at least one constructor, and an array ResetList currentPos


of class objects is declared, then one of the
GetNextItem
constructors must be the default constructor, which
is invoked
15
for each element in the array. 16
Specification of UnsortedType Specification of UnsortedType
Structure: The list has a special property called the current position - int LengthIs
the position of the last element accessed by GetNextItem Function Determines the number of elements in list.
during an iteration through the list. Only ResetList and
GetNextItem affect the current position. Precondition List has been initialized.

Operations (provided by Unsorted List ADT): Postcondition Returns the number of elements in list.

MakeEmpty ItemType GetItem (ItemType item, Boolean& found)

Function Initializes list to empty state. Function Retrieves list element whose key matches item's key (if
present).
Precondition
Precondition List has been initialized. Key member of item is initialized.
Postcondition List is empty.
Postcondition If there is an element someItem whose key matches item's
Boolean IsFull key, then found = true and item is a copy of someItem;
Function Determines whether list is full. otherwise found = false and item is unchanged. List is
Precondition List has been initialized. unchanged.

Postcondition Returns true if list is full and false otherwise. PutItem (ItemType item)
Function Adds item to list.
Precondition List has been initialized. List is not full. item is not in list.
17 18
Postcondition item is in list.

// SPECIFICATION FILE ( UnsortedType.h )


Specification of UnsortedType #include “ItemType.h”

DeleteItem (ItemType item) class UnsortedType // declares a class data


type
Function Deletes the element whose key matches item's key.
{
Precondition List has been initialized. Key member of item is initialized. public :
One and only one element in list has a key matching item's // 8 public member functions
key. UnsortedType ( );
Postcondition No element in list has a key matching item's key. bool IsFull ( ) const;
int GetLength ( ) const ; // returns length of list
ResetList
ItemType GetItem ( ItemType item, bool& found);
Function Initializes current position for an iteration through the list. void PutItem ( ItemType item );
Precondition List has been initialized. void DeleteItem ( ItemType item );
void ResetList ( );
Postcondition Current position is prior to first element in list. ItemType GetNextItem ( );
GetNextItem (ItemType& item)
Function Gets the next element in list. private :
// 3 private data members
Precondition List has been initialized. Current position is defined. int length;
Element at current position is not last in list. ItemType info[MAX_ITEMS];
Postcondition Current position is updated to next position. item is a copy int currentPos;
19 of element at current position. }; 20
Before Inserting Hsing into an
Unsorted List
// IMPLEMENTATION FILE ARRAY-BASED LIST ( unsorted.cpp )
#include “UnsortedType.h”

void UnsortedType::UnsortedType ( ) length 3 The item will


// Pre: None. be placed into
// Post: List is empty. O(1) the length location,
{
info [0] Maxwell and length will be
length = 0; incremented.
[1] Bradley
currentPos = -1;
} [2] Asad

void UnsortedType::PutItem ( ItemType item ) [3]


.
// Pre: List has been initialized. List is not full.
.
// item is not in list.
.
// Post: item is in the list. O(1)
{ [MAX_ITEMS-1]
info[length] = item;
length++; 21

} 21 22

After Inserting Hsing into an int UnsortedType::GetLength( ) const


Unsorted List // Pre: List has been inititalized.
// Post: Function value == ( number of elements in
length 4 // list ).
{ O(1)
return length;
info [0] Maxwell
}
[1] Bradley

[2] Asad bool UnsortedType::IsFull ( ) const


[3] Hsing // Pre: List has been initialized.
. // Post: Function value == ( list is full ). O(1)
. {
. return ( length == MAX_ITEMS );
[MAX_ITEMS-1]
}
24

23 24
Getting Ivan from an Unsorted List
ItemType UnsortedType::GetItem ( ItemType item, bool& found )
// Pre: Key member of item is initialized.
// Post: If found, item’s key matches an element’s key in the list
// and a copy of that element is returned;
// otherwise, input item is returned.
{ length 4 moreToSearch: true
bool moreToSearch;
found: false
int location = 0;
O(N) info [0] Maxwell
found = false; location: 0
moreToSearch = ( location < length ); [1] Bradley
while ( moreToSearch && !found )
{ [2] Asad
switch ( item.ComparedTo( info[location] ) )
{ case LESS : [3] Hsing
case GREATER : location++; .
moreToSearch = ( location < length ); .
break;
case EQUAL : found = true;
[MAX_ITEMS-1]
item = info[ location ];
}
}
return item; 25
} 25 26

Getting Ivan from an Unsorted List


Getting Ivan from an Unsorted List
length 4 moreToSearch: true length 4 moreToSearch: true
found: false
found: false
info [0] Maxwell location: 1 info [0] Maxwell
location: 2
[1] Bradley [1] Bradley

[2] Asad [2] Asad

[3] Hsing [3] Hsing


. .
. .
.
[MAX_ITEMS-1] [MAX_ITEMS-1]

27 28
Getting Ivan from an Unsorted List Getting Ivan from an Unsorted List
length 4 moreToSearch: true
length 4 moreToSearch: false
found: false
info [0] Maxwell found: false
location: 3 info [0] Maxwell
location: 4
[1] Bradley
[1] Bradley
[2] Asad
[2] Asad
[3] Hsing
. [3] Hsing
. .
. .
[MAX_ITEMS-1] .

[MAX_ITEMS-1]

29 30

void UnsortedType::DeleteItem ( ItemType item ) Deleting Bradley from an Unsorted List


// Pre: item’s key has been inititalized.
// An element in the list has a key that matches item’s.
// Post: No element in the list has a key that matches item’s. length 4
{ location: 0
int location = 0 ; info [0] Maxwell

while (item.ComparedTo (info [location] ) != EQUAL ) [1] Bradley


location++; Key Bradley has
[2] Asad not been matched.
// move last element into position where item was located
[3] Hsing
.
.
info [location] = info [length - 1 ] ;
length-- ;
O(N) .
} [MAX_ITEMS-1]

31 32
Deleting Bradley from an Unsorted List
Deleting Bradley from an Unsorted List
length 4 length 4
location: 1
info [0] Maxwell location: 1 info [0] Maxwell

[1] Bradley [1] Hsing


[2] Asad [2] Asad Placed copy of
Key Bradley has last list element
[3] Hsing [3] Hsing into the position
been matched.
. .
where the key Bradley
. .
was before.
. .
[MAX_ITEMS-1]
[MAX_ITEMS-1]

33 34

Deleting Bradley from an void UnsortedType::ResetList ( )

Unsorted List // Pre: List has been inititalized.


// Post: Current position is prior to first element in list.
length 3 {
currentPos = -1;
location: 1 } O(1)
info [0] Maxwell

[1] Hsing ItemType UnsortedType::GetNextItem ()


// Pre: List has been initialized. Current position is defined.
[2] Asad Decremented length. // Element at current position is not last in list.
// Post: Current position is updated to next position.
[3] Hsing
. // item is a copy of element at current position.
. {
. currentPos++; O(1)
[MAX_ITEMS-1] return info [currentPos];
}

35 36
UML Diagrams ItemType
What is a pointer variable?
+RelationType: {LESS, GREATER, EQUAL}
(Array) -value: int
• A pointer variable is a variable whose value is the address of a
+ComparedTo(otherItem:ItemType): RelationType
+Print(ofstream&): void
location in memory.
+Initialize(number:int): void
• To declare a pointer variable, you must specify the type of
value that the pointer will point to. For example,

UnsortedType int* ptr; // ptr will hold the address of an int


-info[MAX_ITEMS]: ItemType
-length: int char* q; // q will hold the address of a char
-currentPos: int

+UnsortedType()
+MakeEmpty(): void
+GetLength(): int
+IsFull(): bool
+GetItem(item:ItemType, found: bool&): ItemType
+PutItem(item:ItemType): void
+DeleteItem(item:ItemType): void
+ResetList(): void
+GetNextItem(): ItemType

37 38

Using a pointer variable Unary operator * is the deference


(indirection) operator
2000 2000
int x; int x;
x = 12; 12 12
x = 12;
x x

int* ptr; 3000 3000


int* ptr;
ptr = &x; 2000 2000
ptr = &x;
ptr ptr

NOTE: Because ptr holds the address of x, std::cout << *ptr;


we say that ptr “points to” x
NOTE: The value pointed to by ptr is denoted by
*ptr
39 40
Using the dereference operator Another Example
char ch; 4000

int x; 2000 ch = ‘A’; A Z


x = 12; 12 5 ch
char* q;
x
q = &ch; 5000 6000
int* ptr; 3000 4000 4000
ptr = &x; 2000 *q = ‘Z’; q p
ptr char* p;
*ptr = 5; // changes the value
// at adddress ptr to 5 p = q; // the right side has value
4000
// now p and q both point to ch
41 42

C++ Data Types Dynamically Allocated Data

2000
char* ptr;
Simple
Structured ptr
ptr = new char;
Integral Floating
array struct union class *ptr = ‘B’;
char short int long enum std::cout << *ptr;

float double long double


Address
New is an operator
pointer reference 43

43 44
Dynamically Allocated Data Dynamically Allocated Data

char* ptr; 2000


2000
char* ptr;

ptr = new char; ptr


ptr
ptr = new char;
*ptr = ‘B’;
*ptr = ‘B’;
std::cout << *ptr; ‘B’
std::cout << *ptr;

NOTE: Dynamic data has no variable name

45 46

Dynamically Allocated Data Yes, but what does new do?


2000 New
char* ptr;
?
• takes a pointer variable,
ptr
ptr = new char;
• allocates memory for it to point, and
*ptr = ‘B’;
std::cout << *ptr; • leaves the address of the assigned
NOTE: Delete memory in the pointer variable.
delete ptr; deallocates
the memory • If there is no more memory, the
pointed to pointer variable is set to NULL.
by ptr.

47 48
The NULL Pointer Using operator delete
There is a pointer constant called NULL
available in cstddef.
NULL is not a memory address; it means that The object or array currently pointed to by the
the pointer variable points to nothing. pointer is deallocated, and the pointer is
considered unassigned. The memory is
It is an error to dereference a pointer whose value returned to the free store.
is NULL. It is the programmer’s job to check for
this. Square brackets are used with delete to deallocate
while (ptr != NULL) a dynamically allocated array of classes.
{
. . . // ok to use *ptr here
}

49 50

What happens here?


Memory Leak

A memory leak occurs when dynamic memory (that was created


int* ptr = new int; 3 using operator new) has been left without a pointer to it by
*ptr = 3; the programmer, and so is inaccessible.
ptr
ptr = new int; // changes value of ptr int* ptr = new int;
*ptr = 4; *ptr = 8; 8
int* ptr2 = new int; ptr
3 *ptr2 = -5;
ptr -5
ptr2
4
How else can an object become inaccessible?

51 52
Causing a Memory Leak A Dangling Pointer

int* ptr = new int; • occurs when two pointers point to the same object and delete
8
is applied to one of them.
*ptr = 8; ptr
int* ptr2 = new int; int* ptr = new int;
-5
*ptr2 = -5; *ptr = 8;
ptr2 int* ptr2 = new int; 8
*ptr2 = -5;
ptr = ptr2; // here the 8 becomes ptr = ptr2;
ptr
inaccessible
8 -5
ptr ptr2

-5
FOR EXAMPLE,
ptr2
53 54

Leaving a Dangling Pointer Remember?


int* ptr = new int;
*ptr = 8; 8 • A list is a homogeneous collection of
int* ptr2 = new int; ptr elements, with a linear relationship
*ptr2 = -5; -5 between elements.
ptr = ptr2; ptr2
• That is, each list element (except the
delete ptr2; // ptr is left dangling
first) has a unique predecessor, and
ptr2 = NULL; 8
each element (except the last) has a
ptr
unique successor.
NULL
ptr2
55 56
ADT Unsorted List Operations #include “ItemType.h” // UnsortedType.h

struct NodeType {
Transformers ItemType info;
NodeType* next;
• MakeEmpty };
change state
• PutItem class UnsortedType
• DeleteItem {
Observers public : // LINKED LIST IMPLEMENTATION
• IsFull // The public interface is the same
• GetLength observe state
private :
• GetItem // The private part is different
NodeType* listData;
int length;
Iterators NodeType* currentPos;
• ResetList process all
}; Do we have to keep a length field?
• GetNextItem Do we need an IsFull? 58

57 58

class UnsortedType // LINKED LIST IMPLEMENTATION ( UnsortedType.cpp )


#include “UnsortedType.h”

UnsortedType::UnsortedType ( ) // constructor
UnsortedType // Pre: None.

MakeEmpty
Private data: // Post: List is empty. O(1)
{
length 3 length = 0;
~UnsortedType listData = NULL;
listData ‘X’ ‘C’ ‘L’ currentPos = NULL;
GetItem
}
PutItem currentPos ?
int UnsortedType::GetLength( ) const
DeleteItem // Post: Function value = number of items in the list.
.
. {
. return length;
GetNextItem
} O(1)
60

59 60
ItemType UnsortedType::GetItem( ItemType item, bool& found )
// Pre: Key member of item is initialized.
void UnsortedType::PutItem ( ItemType item )
// Post: If found, item’s key matches an element’s key in the list
// a copy of that element is returned; otherwise, // Pre: list is not full and item is not in list.
// origianl item is returned. // Post: item is in the list; length has been incremented.
{ bool moreToSearch;
NodeType* location; {
location = listData;
found = false ;
O(N) NodeType* location; O(1)
// obtain and fill a node
moreToSearch = ( location != NULL );
while ( moreToSearch && !found ) location = new NodeType;
{ switch( item.ComparedTo( location->info ) location->info = item;
{ // match
case LESS: location->next = listData;
case GREATER: // advance pointer listData = location;
location = location->next;
moreToSearch = ( location != NULL );
length++;
break; }
case EQUAL:
found = true;
item = location->info;
}
61 62
}
return
61 item; 62
}

location = new NodeType;


Inserting ‘B’ into an Unsorted List item ‘B’

location

Private data: Private data:


length 3 length 3

listData ‘X’ ‘C’ ‘L’ listData ‘X’ ‘C’ ‘L’

currentPos ? currentPos ?

63 64
item ‘B’ location->info = item ; item ‘B’ location->next = listData ;

location ‘B’ location ‘B’

Private data: Private data:


length 3 length 3

listData ‘X’ ‘C’ ‘L’ listData ‘X’ ‘C’ ‘L’

currentPos ? currentPos ?

65 66

item
listData = location ; item
length++ ;
‘B’ ‘B’

location ‘B’ location ‘B’

Private data: Private data:


length 3 length 4

listData ‘X’ ‘C’ ‘L’ listData ‘X’ ‘C’ ‘L’

currentPos ? currentPos ?

67 68
void UnsortedType::DeleteItem( ItemType item )
// Pre: item’s key has been initialized.
// An element of the list has a key that matches item’s
// Post: No element of the list has a key that matches item’s
{
item ‘M’ location = listData ;
NodeType* location = listData;
NodeType* tempLocation;

// Locate node to be deleted O(N) location tempLocation


if( item.ComparedTo(location->info) == EQUAL )
{
tempLocation = location;
listData = listData->next;
// Save pointer to node
// Delete first node
Private data:
}
else length 4
{
while( item.ComparedTo(location->next->info) != EQUAL ) listData ‘X’ ‘C’ ‘M’ ‘L’
location = location->next;

// Delete node at location->next


currentPos ?
tempLocation = location->next;
location->next = location->next->next;
}
delete tempLocation; // Return node
length--;
} 69 70

item ‘M’ location->info = ‘X’ ; item ‘M’ location->next->info = ‘C’ ;

location tempLocation location tempLocation

Private data: Private data:


length 4 length 4

listData ‘X’ ‘C’ ‘M’ ‘L’ listData ‘X’ ‘C’ ‘M’ ‘L’

currentPos ? currentPos ?

71 72
item ‘M’ location = location->next; item ‘M’ location->next->info = ‘M’;

location tempLocation location tempLocation

Private data: Private data:


length 4 length 4

listData ‘X’ ‘C’ ‘M’ ‘L’ listData ‘X’ ‘C’ ‘M’ ‘L’

currentPos ? currentPos ?

73 74

item ‘M’ tempLocation = location->next; item ‘M’ location->next = location->next->next;

location tempLocation location tempLocation

Private data: Private data:


length 4 length 4

listData ‘X’ ‘C’ ‘M’ ‘L’ listData ‘X’ ‘C’ ‘M’ ‘L’

currentPos ? currentPos ?

75 76
item ‘M’ delete tempLocation; item ‘M’ length--;

location tempLocation location tempLocation

Private data: Private data:


length 4 length 3
listData ‘X’ ‘C’ ‘L’ listData ‘X’ ‘C’ ‘L’

currentPos ? currentPos ?

77 78

void UnsortedType::MakeEmpty() void UnsortedType::ResetList()


// Post: list is empty; all items have been deallocated // Post: currentPos has been initialized.
{ {
NodeType* tempPtr; currentPos = NULL; O(1)
}
// Locate node to be deleted
while( listData != NULL )
bool UnsortedType::IsFull() const
O(N)
{
// Post: Return true if there is no room for another ItemType
tempPtr = listData;
// on the free store; false otherwise
listData = listData->next;
delete tempPtr;
{
} NodeType* location;
length = 0; try
} {
location = new NodeType;
ItemType UnsortedType::GetNextItem() delete location;
// Post: A copy of the next item in the list is returned. return false;
//
//
When the end of the list is reached, currentPos
is reset to begin again.
O(1) } O(1)
catch(bad_alloc &exception)
{ {
if(currentPos == NULL) return true;
currentPos = listData; }
else }
currentPos = currentPos->next; 79 80
return currentPos->info;
} 79 80
UML Diagrams ItemType COMPARISON
+RelationType: {LESS, GREATER, EQUAL}
(LinkedList) -value: int

+ComparedTo(otherItem:ItemType): RelationType
+Print(ofstream&): void
+Initialize(number:int): void
Operation Array LinkedList
UnsortedType O(1) O(1)
MakeEmpty O(1) O(n)
UnsortedType
GetLength O(1) O(1)
-listData: NodeType*
-length: int IsFull O(1) O(1)
-currentPos: NodeType*
GetItem O(n) O(n)
+UnsortedType()
+MakeEmpty(): void PutItem O(1) O(1)
+GetLength(): int
+IsFull(): bool
DeleteItem O(n) O(n)
+GetItem(item:ItemType, found: bool&): ItemType
+PutItem(item:ItemType): void
ResetList O(1) O(1)
+DeleteItem(item:ItemType): void GetNextItem O(1) O(1)
+ResetList(): void
+GetNextItem(): ItemType

81 82

You might also like