Professional Documents
Culture Documents
Overview
Recursion
Singly-Linked Lists
Abstract Data Types
References
Bruno R. Preiss: Data Structures and Algorithms with Object-
Oriented Design Patterns in C++. John Wiley & Sons, Inc. (1999)
Richard F. Gilberg and Behrouz A. Forouzan: Data Structures - A
Pseudocode Approach with C. 2nd Edition. Thomson (2005)
Russ Miller and Laurence Boxer: Algorithms Sequential & Parallel.
2nd Edition. Charles River Media Inc. (2005)
Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo: C++ Primer.
4th Edition. Addison-Wesley (2006)
58
Recursion
If a procedure that contains within its body calls to itself,
then this procedure is called to be recursively defined.
59
Impossible Structures
60
1
Application of Recursion
X =… X …
61
Factorials
n! = n * (n - 1) * … * 1
"
1 if n = 0
n! =
$$
#
$
n * (n - 1)! if n > 0
$%
62
Calculating Factorials
The recursive definition tells us exactly how to calculate a
factorial:
63
2
Recursive Factorial
64
Towers of Hanoi
Problem:
Move disks from a start peg to a target peg using a
middle peg.
Challenge:
All disks have a unique size and at no time must a bigger
disk be placed on top of a smaller one.
65
Finish:
3
A Recursive Solution
1. Move n–1 disks from Start to Middle:
S M T
67
S M T
2:
S M T
3:
S M T
4:
68
69
4
Recursion is a prerequisite for linked lists!
70
71
3 5 29 20 4
Delete 5
29 20 4
3 29 20 4
72
5
Addition Requires Shift
3 29 20 4
Insert 50 after 29
20 4
3 29 50 20 4
73
Linked Lists
A linked list is a sequence of data items, each connected to
the next by a pointer called next.
74
Nodes
DataType is application-specific
class Node
{
public:
DataType data;
Node* next;
75
6
Can we be more specific?
76
Templates
77
78
7
Class Template Instantiation
79
80
Node Construction
p 5 Nil
q 7 5 Nil
81
8
Node Access
Node<int> *p, *q;
p = new Node<int>( 5, (Node<int>*)0 );
q = new Node<int>( 7, p );
a = p->data;
b = q->next->data;
a: p 5 Nil
b: q 7 5 Nil
82
Insert a Node
Node<int> r*;
p 5 Nil
q 7 6 5 Nil
r 6 5 Nil
Delete a Node
q 7 6 5 Nil
q->next = q->next->next;
p 5 Nil
q 7 5 Nil
r 6 5 Nil
9
Insert at the Beginning
pList 5 Nil
pList 7 5 Nil
85
86
pList 5 7 Nil
pToEnd * 9 Nil
pList 5 7 9 Nil
87
10
Insert at the end preserves the order
of list nodes!
88
if ( *pList == (Node<int>*)0 )
{
pLastNode = pNewNode; // make new node last
pList = pLastNode; // set first node
}
else
{
pLastNode->next = pNewNode; // append new node
pLastNode = pNewNode; // make new node last
}
89
90
11