C Plus Data Structures - PowerPoint PPT Presentation

1 / 129
About This Presentation
Title:

C Plus Data Structures

Description:

... first element into the allocated space. Fig. 5.5. Somewhere in free ... Lost in space! 37. Fig 5.10 Pointer dereferencing and member selection. A' (a) location ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 130
Provided by: sylv147
Category:
Tags: data | in | lost | plus | space | structures

less

Transcript and Presenter's Notes

Title: C Plus Data Structures


1
C Plus Data Structures
  • Nell Dale
  • David Teague
  • Chapter 5
  • Linked Structures
  • Slides by Sylvia Sorkin, Community College of
    Baltimore County - Essex Campus

2
Linked Structures
  • To be able to implement the Stack ADT as a linked
    data structure
  • To be able to implement the Queue ADT as a linked
    data structure
  • To be able to implement the Unsorted List ADT as
    a linked data structure
  • To be able to implement the Sorted List ADT as a
    linked data structure
  • To be able to compare alternative implementations
    of an abstract data type with respect to
    performance

3
Definition of Stack
  • Logical (or ADT) level A stack is an ordered
    group of homogeneous items (elements), in which
    the removal and addition of stack items can take
    place only at the top of the stack.
  • A stack is a LIFO last in, first out structure.

4
Stack ADT Operations
  • MakeEmpty -- Sets stack to an empty state.
  • IsEmpty -- Determines whether the stack is
    currently empty.
  • IsFull -- Determines whether the stack is
    currently full.
  • Push (ItemType newItem) -- Adds newItem to the
    top of the stack.
  • Pop (ItemType item) -- Removes the item at the
    top of the stack and returns it in item.

4
5
ADT Stack Operations
  • Transformers
  • MakeEmpty
  • Push
  • Pop
  • Observers
  • IsEmpty
  • IsFull

change state observe state
5
6
Another Stack Implementation
  • One advantage of an ADT is that the kind of
    implementation used can be changed.
  • The dynamic array implementation of the stack has
    a weakness -- the maximum size of the stack is
    passed to the constructor as parameter.
  • Instead we can dynamically allocate the space for
    each stack element as it is pushed onto the
    stack.

7

class StackTypeltchargt
8

class StackTypeltfloatgt
23.4 -7.9
9

class StackTypeltStrTypegt
10
Tracing Client Code
V
letter
11
Tracing Client Code
letter
V
Private data topPtr NULL
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

12
Tracing Client Code
letter
V
Private data topPtr
V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

13
Tracing Client Code
letter
V
Private data topPtr
C V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

14
Tracing Client Code
letter
V
Private data topPtr
S C V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

15
Tracing Client Code
letter
V
Private data topPtr
S C V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

16
Tracing Client Code
letter
S
Private data topPtr
C V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

17
Tracing Client Code
letter
S
Private data topPtr
K C V
char letter V StackTypelt char gt
myStack myStack.Push(letter) myStack.Push(C)
myStack.Push(S) if ( !myStack.IsEmpty( )
) myStack.Pop( letter ) myStack.Push(K)

18
Dynamically Linked Implementation of Stack
  • // DYNAMICALLY LINKED IMPLEMENTATION OF STACK
  • include "ItemType.h" // for ItemType
  • templateltclass ItemTypegt
  • struct NodeType
  • ItemType info
  • NodeTypeltItemTypegt next

18
19
  • // DYNAMICALLY LINKED IMPLEMENTATION OF STACK
    continued
  • templateltclass ItemTypegt
  • class StackType
  • public
  • StackType( ) // constructor
  • // Default constructor.
  • // POST Stack is created and empty.
  • void MakeEmpty( )
  • // PRE None.
  • // POST Stack is empty.
  • bool IsEmpty( ) const
  • // PRE Stack has been initialized.
  • // POST Function value (stack is empty)
  • bool IsFull( ) const
  • // PRE Stack has been initialized.
  • // POST Function value (stack is full)

19
20
  • // DYNAMICALLY LINKED IMPLEMENTATION OF STACK
    continued
  • void Push( ItemType item )
  • // PRE Stack has been initialized.
  • // Stack is not full.
  • // POST newItem is at the top of the stack.
  • void Pop( ItemType item )
  • // PRE Stack has been initialized.
  • // Stack is not empty.
  • // POST Top element has been removed from
    stack.
  • // item is a copy of removed element.
  • StackType( ) // destructor
  • // PRE Stack has been initialized.
  • // POST Memory allocated for nodes has been
  • // deallocated.
  • private
  • NodeTypeltItemTypegt topPtr

20
21
  • // DYNAMICALLY LINKED IMPLEMENTATION OF STACK
    continued
  • // member function definitions for class
    StackType
  • templateltclass ItemTypegt
  • StackTypeltItemTypegtStackType( ) //
    constructor
  • topPtr NULL
  • templateltclass ItemTypegt
  • void StackTypeltItemTypegtIsEmpty( ) const
  • // Returns true if there are no elements
  • // on the stack false otherwise
  • return ( topPtr NULL )

21
22
Using operator new
  • If memory is available in an area called the free
    store (or heap), operator new allocates the
    requested object, and returns a pointer to the
    memory allocated.
  • The dynamically allocated object exists until the
    delete operator destroys it.

22
23
Function Push
  • We can modify function Push
  • Allocate space for new item
  • Put new item into the allocated space
  • Put the allocated space into the stack
  • itemPtr new ItemType

23
24
Putting new element into the allocated space
  • Fig. 5.1

Somewhere in free store
E
itemPtr
25
After four calls to Push
Somewhere in free store
  • Fig. 5.2

A
E
D
L
26
One way to keep track of the pointers
  • To declare the stack as an array of pointers and
    put the pointer to each new item into this array,
    as shown in Fig. 5.3

26
27
One way to keep track of the pointers
Stack
0
A
E
1
2
D
L
3
. . . .
. . .
99
Fig. 5.3
28
The other way Chaining the stack elements
together
  • Fig. 5.4

E
A
L
D
29
Pushing the first element into the allocated space
  • Fig. 5.5

Somewhere in free store
D
topPtr
30
Fig 5.6 A single node
.info
.next
D
The users data
Pointer to the next node in the stack
31
Fig 5.7 Node terminology
Node (location)

.info
Info
topPtr
Next(location)
(location)
32
Fig 5.8(a) new(location)
location
D
topPtr
33
Fig 5.8(b) info(location)?newElement
A
location
D
topPtr
34
Fig 5.8(c) Make next (location) point to
Stacks top node
A
location
D
topPtr
35
Fig 5.8(d) Make Stack point to the new node
A
location
D
topPtr
36
Fig 5.9 Be careful when you change pointers
A
location
D
Lost in space!
topPtr
37
Fig 5.10 Pointer dereferencing and member
selection
A
(a) location
A
(b) location
A
(c) location -gtinfo
38
Fig 5.11(a) Pushing onto an empty stack
A
location
topPtr
39
Fig 5.11(b) Pushing onto an empty stack
A
location
topPtr
40
Fig 5.11(c) Pushing onto an empty stack
A
location
topPtr
41
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

42
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

location
43
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

location
44
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

location
45
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

B
location
46
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

B
location
47
Adding newItem to the stack
newItem
B
  • newItem B
  • NodeTypeltchargt location
  • location new NodeTypeltchargt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

X C L
B
location
48
Implementing Push
  • templateltclass ItemTypegt
  • void StackTypeltItemTypegtPush ( ItemType newItem
    )
  • // Adds newItem to the top of the stack.
  • if (IsFull())
  • throw PushOnFullStack()
  • NodeTypeltItemTypegt location
  • location new NodeTypeltItemTypegt
  • location-gtinfo newItem
  • location-gtnext topPtr
  • topPtr location

48
49
Using operator delete
  • The object currently pointed to by the pointer is
    deallocated, and the pointer is considered
    unassigned. The memory is returned to the free
    store.

49
50
Function Pop
  • We can modify function Pop
  • Set item to Info(top node)
  • Unlink the top node from the stack
  • Deallocate the old top node

50
51
Fig 5.12(a) Popping the top element
Y
topPtr
Z
X
Z
item
52
Fig 5.12(b) Popping the top element
Y
topPtr
Z
X
To be deallocated
53
Fig 5.13(a) Popping the stack
Y
topPtr
Z
X
Z
item
54
Fig 5.13(b) Popping the stack
Y
topPtr
Z
X
tempPtr
55
Fig 5.13(c) Popping the stack
Y
topPtr
Z
X
tempPtr
56
Fig 5.13(d) Popping the stack
Y
topPtr
Poof
X
delete tempPtr
57
Fig 5.14(a) Poping the last element on the stack
X
topPtr
X
item
58
Fig 5.14(b) Poping the last element on the stack
X
location
topPtr
59
Fig 5.14(c) Poping the last element on the stack
Poof
topPtr
delete tempPtr
60
Deleting item from the stack
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

B X C L
tempPtr
61
Deleting item from the stack
item
B
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

B X C L
tempPtr
62
Deleting item from the stack
item
B
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

B X C L
tempPtr
63
Deleting item from the stack
item
B
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

B X C L
tempPtr
64
Deleting item from the stack
B
item
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

X C L
tempPtr
65
Implementing Pop
  • templateltclass ItemTypegt
  • void StackTypeltItemTypegtPop ( ItemType item )
  • // Removes element at the top of the stack and
  • // returns it in item.
  • if (IsEmpty())
  • throw PopOnEmptyStack()
  • NodeTypeltItemTypegt tempPtr
  • item topPtr-gtinfo
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr

65
66
  • templateltclass ItemTypegt
  • bool StackTypeltItemTypegtIsFull( ) const
  • // Returns true if there is no room for another
    NodeType // node on the free store false
    otherwise.
  • NodeTypeltItemTypegt location
  • try
  • location new NodeTypeltItemTypegt
  • delete location
  • return false
  • catch(bad_alloc exception)
  • return true

66
67
  • // Alternate form that works with older compilers
  • templateltclass ItemTypegt
  • bool StackTypeltItemTypegtIsFull( ) const
  • // Returns true if there is no room for another
    NodeType // node on the free store false
    otherwise.
  • NodeTypeltItemTypegt location
  • location new NodeTypeltItemTypegt
  • if ( location NULL )
  • return true
  • else
  • delete location
  • return false

67
68
Why is a destructor needed?
  • When a local stack variable goes out of scope,
    the memory space for data member topPtr is
    deallocated. But the nodes that topPtr points to
    are not automatically deallocated.
  • A class destructor is used to deallocate the
    dynamic memory pointed to by the data member.

69
  • templateltclass ItemTypegt
  • void StackTypeltItemTypegtMakeEmpty( )
  • // Post Stack is empty all elements
    deallocated.
  • NodeTypeltItemTypegt tempPtr
  • while ( topPtr ! NULL )
  • tempPtr topPtr
  • topPtr topPtr-gtnext
  • delete tempPtr
  • templateltclass ItemTypegt
  • StackTypeltItemTypegtStackType( ) // destructor
  • MakeEmpty( )

69
70
What is a Queue?
  • Logical (or ADT) level A queue is an ordered
    group of homogeneous items (elements), in which
    new elements are added at one end (the rear), and
    elements are removed from the other end (the
    front).
  • A queue is a FIFO first in, first out structure.

71
Queue ADT Operations
  • MakeEmpty -- Sets queue to an empty state.
  • IsEmpty -- Determines whether the queue is
    currently empty.
  • IsFull -- Determines whether the queue is
    currently full.
  • Enqueue (ItemType newItem) -- Adds newItem to
    the rear of the queue.
  • Dequeue (ItemType item) -- Removes the item at
    the front of the queue and returns it in item.

71
72
ADT Queue Operations
  • Transformers
  • MakeEmpty
  • Enqueue
  • Dequeue
  • Observers
  • IsEmpty
  • IsFull

change state observe state
72
73
Fig 5.15 A linked queue representation
qRear
qFront
74
Fig 5.16 The enqueue operation
qRear
qFront
New node
newNode
75
Fig 5.17 A bad queue design
qRear
qFront
To enqueue, use the Push algorithm
To dequeue, we must be able to reset qfront to
point to the preceding node. But we cant get
there from here.
76
Fig 5.18 The Dequeue operation
qRear
qFront
tempPtr
Info
item
77
class QueTypeltchargt
QueType
Private Data qFront qRear
QueType
Enqueue
Dequeue . . .
78
  • // DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE
  • include "ItemType.h" // for ItemType
  • templateltclass ItemTypegt
  • class QueType
  • public
  • QueType( ) // CONSTRUCTOR
  • QueType( ) // DESTRUCTOR
  • bool IsEmpty( ) const
  • bool IsFull( ) const
  • void Enqueue( ItemType item )
  • void Dequeue( ItemType item )
  • void MakeEmpty( )
  • private
  • NodeTypeltItemTypegt qFront
  • NodeTypeltItemTypegt qRear

78
79
  • // DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE
    continued
  • // member function definitions for class QueType
  • templateltclass ItemTypegt
  • QueTypeltItemTypegtQueType( ) // CONSTRUCTOR
  • qFront NULL
  • qRear NULL
  • templateltclass ItemTypegt
  • bool QueTypeltItemTypegtIsEmpty( ) const
  • return ( qFront NULL )

79
80
  • templateltclass ItemTypegt
  • void QueTypeltItemTypegtEnqueue( ItemType newItem
    )
  • // Adds newItem to the rear of the queue.
  • // Pre Queue has been initialized.
  • // Queue is not full.
  • // Post newItem is at rear of queue.
  • NodeTypeltItemTypegt ptr
  • ptr new NodeTypeltItemTypegt
  • ptr-gtinfo newItem
  • ptr-gtnext NULL
  • if ( qRear NULL )
  • qFront ptr
  • else
  • qRear-gtnext ptr
  • qRear ptr

80
81
  • templateltclass ItemTypegt
  • void QueTypeltItemTypegtDequeue( ItemType item )
  • // Removes element from from front of queue
  • // and returns it in item.
  • // Pre Queue has been initialized.
  • // Queue is not empty.
  • // Post Front element has been removed from
    queue.
  • // item is a copy of removed element.
  • NodeTypeltItemTypegt tempPtr
  • tempPtr qFront
  • item qFront-gtinfo
  • qFront qFornt-gtnext
  • if ( qFront NULL )
  • qRear NULL
  • delete tempPtr

81
82
Fig 5.19 A circular linked queue representation
qRear
Front of queue
Rear of queue
83
What is a List?
  • A list is a homogeneous collection of elements,
    with a linear relationship between elements.
  • That is, each list element (except the first) has
    a unique predecessor, and each element (except
    the last) has a unique successor.

84
Fig 5.21 Honor roll list with two
items(ResetList has not been called)
list
2
.length
?
.currentPos
Lilia
Becca
.listData
85
ADT Unsorted List Operations
  • Transformers
  • MakeEmpty
  • InsertItem
  • DeleteItem
  • Observers
  • IsFull
  • LengthIs
  • RetrieveItem
  • Iterators
  • ResetList
  • GetNextItem

85
86
  • include ItemType.h // unsorted.h
  • . . .
  • template ltclass ItemTypegt
  • class UnsortedType
  • public // LINKED LIST IMPLEMENTATION
  • UnsortedType ( )
  • UnsortedType ( )
  • void MakeEmpty ( )
  • bool IsFull ( ) const
  • int LengthIs ( ) const
  • void RetrieveItem ( ItemType item,
    bool found )
  • void InsertItem ( ItemType item )
  • void DeleteItem ( ItemType item )
  • void ResetList ( )
  • void GetNextItem ( ItemType item )
  • private
  • NodeTypeltItemTypegt listData
  • int length

86
87

class UnsortedTypeltchargt
UnsortedType
Private data length
3 listData currentPos
MakeEmpty
UnsortedType
RetrieveItem
InsertItem
DeleteItem . . .
GetNextItem
88
  • // LINKED LIST IMPLEMENTATION ( unsorted.cpp )
  • include itemtype.h
  • template ltclass ItemTypegt
  • UnsortedTypeltItemTypegtUnsortedType ( ) //
    constructor
  • // Pre None.
  • // Post List is empty.
  • length 0
  • listData NULL
  • template ltclass ItemTypegt
  • int UnsortedTypeltItemTypegtLengthIs ( ) const
  • // Post Function value number of items in the
    list.
  • return length

88
89
  • // LINKED LIST IMPLEMENTATION ( unsorted.cpp )
  • include itemtype.h
  • template ltclass ItemTypegt
  • UnsortedTypeltItemTypegtUnsortedType ( ) //
    constructor
  • // Pre None.
  • // Post List is empty.
  • length 0
  • listData NULL
  • template ltclass ItemTypegt
  • int UnsortedTypeltItemTypegtLengthIs ( ) const
  • // Post Function value number of items in the
    list.
  • return length

89
90
Function RetrieveItem
  • The algorithm
  • Initialize location to listData
  • Set found to false
  • Set moreToSearch to (location !Null)
  • while moreToSearch AND NOT found
  • switch(item.ComparedTo(location-gt info))
  • case LESS
  • case Greater Set location to location-gtnext
  • Set moreToSearch to(location!NULL)
  • case EQUAL Set found to true
  • Set item to location -gtinfo

91
Fig 5.22 Retrieving an item in an unsorted linked
list
We want to examine the value of location at the
end. There are two cases 1. location NULL. If
we reach the end of the list without finding an
item whose key is equal to items key, then the
item is not in the list. Location correctly has
the null pointer value
(a) Retrieve Kit
John
Lilia
Kate
Becca
listData
moreToSearch false found
false location NULL
92
Fig 5.22 Retrieving an item in an unsorted linked
list
2. Item.ComparedTo(location-gtinfo) EQUAL. In
this case, we have found the element and have
copied it into item
(b) Retrieve Lilia
John
Lilia
Kate
Becca
listData
moreToSearch true found true
location
93
  • template ltclass ItemTypegt
  • void UnsortedTypeltItemTypegtRetrieveItem(
    ItemType item, bool found )
  • // Pre Key member of item is initialized.
  • // Post If found, items key matches an
    elements key in the list and a copy
  • // of that element has been stored in item
    otherwise, item is unchanged.
  • bool moreToSearch
  • NodeTypeltItemTypegt location
  • location listData
  • found false
  • moreToSearch ( location ! NULL )
  • while ( moreToSearch !found )
  • if ( item location-gtinfo )
    // match here
  • found true
  • item location-gtinfo
  • else // advance pointer
  • location location-gtnext
  • moreToSearch ( location ! NULL )

93
94
Function InsertItem
  • In the array-based list, we put the new item at
    the end
  • In the Linked list at the beginning of the
    list.Because the list is unsorted,we can put the
    new item wherever, we chooseat the front of the
    list. So algorithm for InsertItem is identical to
    Push in the linked stack.

95
  • template ltclass ItemTypegt
  • void UnsortedTypeltItemTypegtInsertItem (
    ItemType item )
  • // Pre list is not full and item is not in
    list.
  • // Post item is in the list length has been
    incremented.
  • NodeTypeltItemTypegt location
  • // obtain and fill a node
  • location new NodeTypeltItemTypegt
  • location-gtinfo item
  • location-gtnext listData
  • listData location
  • length

95
96

Inserting B into an Unsorted List
97

location new NodeTypeltItemTypegt
item location
B
98

location-gtinfo item
item location
B
B
99

location-gtnext listData
B
item location
B
100

listData location
item location
B
B
Private data length
3 listData currentPos
101

length
item location
B
B
Private data length
4 listData currentPos
102
Function DeleteItem
  • 1. We must first find an item(Fig5.22(b))
  • location is left pointing to the node that
    contains the item for which we are searching
  • 2. To remove it, we must change the pointer in
    the previous node to the next data member of the
    one being deleted(see Fig5.23a)

103
Fig 5.22 Retrieving an item in an unsorted linked
list
2. Item.ComparedTo(location-gtinfo) EQUAL. In
this case, we have found the element and have
copied it into item
(b) Retrieve Lilia
John
Lilia
Kate
Becca
listData
moreToSearch true found true
location
104
Fig 5.23 Deleting an interior node and deleting
the first node
(a) Delete Lilia
John
Lilia
Kate
Becca
listData
moreToSearch true found true
location
105
Fig 5.23 Deleting an interior node and deleting
the first node
(b) Delete Kate
John
Lilia
Kate
Becca
listData
location
106

class SortedTypeltchargt
SortedType
Private data length
3 listData currentPos
MakeEmpty
SortedType
RetrieveItem
InsertItem
DeleteItem . . .
GetNextItem
107
InsertItem algorithm for Sorted Linked List
  • Set location to listData
  • Set moreToSearch to (location !Null)
  • while moreToSearch
  • switch (item.ComparedTo(location-gtinfo))
  • case GREATER Set location to location-gtnext
  • Set moreToSearch to (location!NULL)
  • case LESS Set moreToSearch to false

108
Fig 5.24 Retrieving an item in a sorted linked
list
This algorithm(slide 103) would crash because
location --gtnext would be null
Retrieve Kit
Lilia
John
Becca
Kate
listData
moreToSearch false found false
location
109
Fig 5.25 Inserting an item in a sorted linked list
This algorithm(slide 103) would crash because
location --gtnext would be null
Insert Sara
Lilia
John
Becca
Kate
listData
moreToSearch true location

110
InsertItem algorithm for Sorted Linked List
  • Find proper position for the new element in the
    sorted list using two pointers predLoc and
    location, where predLoc trails behind location.
  • Obtain a node for insertion and place item in it.
  • Insert the node by adjusting pointers.
  • Increment length.

111
InsertItem algorithm for Sorted Linked List
  • Set location to listData
  • Set predloc to NULL
  • Set moreToSearch to (location !Null)
  • while moreToSearch
  • switch (item.ComparedTo(location-gtinfo))
  • case GREATER Set predLoc to
    location Set location to location-gtnext
  • Set moreToSearch to (location!NULL)
  • case LESS Set moreToSearch to
    false
  • Set newNode to the address of a newly allocated
    node
  • Set newNode-gtinfo to item
  • Set newNode-gtnext to location
  • Set predLoc-gtnext to newNode
  • Increment length

112
Fig 5.26 Inserting an item in a sorted linked list
This algorithm using predloc and set it to NULL
(a)
predloc
location
Lilia
John
Becca
Kate
listData
113
Fig 5.26 The inchworm effect
This algorithm using predloc and set it to NULL
(b) Set predloc to location
predloc
location
Lilia
John
Becca
Kate
listData
114
Fig 5.26 Inserting an item in a sorted linked list
This algorithm using predloc and set it to NULL
c. Set location to Next(location)
predloc
location
Lilia
John
Becca
Kate
listData
115
Fig 5.27 Four insertion cases
This algorithm using predloc and set it to NULL
(a) Insert Alex(goes at the beginning)
listData
Becca
Alex
predloc
location
newNode
116
Fig 5.27 Four insertion cases
This algorithm using predloc and set it to NULL
(b) Insert Kit(goes in the middle)
John
Kate
listData
Lilia
Kit
predloc
location
newNode
117
Fig 5.27 Four insertion cases
This algorithm using predloc and set it to NULL
(c) Insert Kate(goes at the end)
Alex
Chris
listData
Kate
predloc
location
newNode
118
Fig 5.27 Four insertion cases
This algorithm using predloc and set it to NULL
(d) Insert John(into an empty list)
listData
John
newNode
predloc
location
119
Implementing SortedType member function
InsertItem

// LINKED LIST IMPLEMENTATION
(sorted.cpp) include ItemType.h template
ltclass ItemTypegt void SortedTypeltItemTypegt
InsertItem ( ItemType item ) // Pre List has
been initialized. List is not full. item is not
in list. // List is sorted by key member. //
Post item is in the list. List is still
sorted. . . .
120

Inserting S into a Sorted List
predLoc location
Private data length
3 listData currentPos
121

Finding proper position for S
predLoc location
NULL
Private data length
3 listData currentPos
122

Finding proper position for S
predLoc location
Private data length
3 listData currentPos
123

Finding proper position for S
predLoc location
Private data length
3 listData currentPos
124

Inserting S into proper position
predLoc location
Private data length
4 listData currentPos
C L X
125
Fig 5.28 Deleting from a linked list
This Algorithm starts as same with a search. In
this case we exit the searching loop when
item.ComparedTo(location-gtinfo) returns EQUAL.
Once we have found the item, we delete it.
Because our precondition states that the item to
be deleted is in the list, we have a choice. We
can use the unordered list algorithm exactly as
it is or we can write an algorithm that is the
mirror image of the insertion. The four cases
that occur are represented in follow Fig 5.28
126
Fig 5.28 Deleting from a linked list(a) Delete
only list node(Delete David)
Delete David
NULL
David
listData
predloc
location
127
Fig 5.28 Deleting from a linked list(b) Delete
first list node(Delete David)
Delete David
Miriam
Johua
David
Leah
listData
predloc
location
128
Fig 5.28 Deleting from a linked list(c) Delete
middle node(Delete Leah)
Delete Leah
Miriam
Johua
David
Leah
listData
predloc
location
129
Fig 5.28 Deleting from a linked list(d) Delete
last node(Delete Miriam)
Delete Miriam
Null
Miriam
Johua
David
Leah
listData
predloc
location
Write a Comment
User Comments (0)
About PowerShow.com