stacks, queues and hierarchical collectionsvladestivill-castro.net/teaching/prog3/p3-06.pdf ·...
TRANSCRIPT
�
Stacks, Queues and Hierarchical Collections
Stacks, Queues and Hierarchical Collections
2501ICTLogan
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
2
�
ContentsContents
• Linked Data Structures Revisited• Stacks• Queues
• Trees• Binary Trees• Generic Trees
• Implementations
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
3
�
Queues and StacksQueues and Stacks
• Linear Collections• Can be implemented in different ways, e.g.
• Arrays• Linked Lists
• Are often used in Operating Systems and run time environments• Function/Method calling Stacks• Process priority Queues
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
4
�
QueuesQueues
• FIFO collections• First element enqueued is first to be dequeued• Insertions occur at one end, the rear• Removals occur at the other end, the front
• Priority Queue Extensions• Reordering according to priority• Few priorities: multiple Queues• Many priorities: insert according to priority
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
5
�
Queues using ListsQueues using Lists
• Use the head and tail Pointers
• Enqueue: Insert from the tail (rear)• Dequeue: Remove from the head
(front)
data
NULLhead
rearfrontNULL
tail
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
6
�
Priority QueuesPriority Queues
• Implementation #1: Multiple Lists• One list per priority• Enqueue on the corresponding list• Dequeue starting at the highest priority list
• Go to next lower priority if empty, etc.• Does not require search operation to enqueue• Requires two pointers (head/tail) per priority:
• Faster enqueue, but slower dequeue operationUseful if number of different priorities is small
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
7
�
Priority Queues (2)Priority Queues (2)
• #2: Priority Ordering• Only one list• Enqueue according to priority
• Higher priority entries “overtake” lower ones
• Dequeue always from the head• Requires linear search to enqueue: O(n)
• Dequeue doesn’t require search: O(1)• Useful if number of different priorities is large
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
8
�
Queue ApplicationsQueue Applications
• First-Come-First Serve Algorithms→ OS Process Scheduling→ Event Handling→ Modeling and Simulation of
Real-World Processes• E.g. checkout queue in a supermarket
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
9
�
StacksStacks
• LIFO collection• The last element pushed onto the stack is the
first to be retrieved• Both push (insertion) and pop (deletion)
operations occur at the top of the stack
• Implementation• Arrays• Singly linked lists
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
10
�
Array ImplementationArray Implementation
• Index: i = 0;• Push: stack[i++] = element;
• Pop: element = stack[--i];
• Peek: element = stack[i-1];• “Sneak preview,” without changing i
• Watch Preconditions!
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
11
�
Stack ExampleStack Example
• Parsing Matching Parenthesis• expression = { letter } | “(” expression “)”
| “[” expression “]”
• “either a letter or an expression in brackets”
• Legal examples• a ab (a) (ab) [(a)] [a(b)cd]
• Illegal examples• a) )( a( [[(]) [a)a]
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
12
�
Matching () AlgorithmMatching () Algorithm
• For each character c in the String• If c is (, [, or {
• Push c onto the stack
• Else if c is ), ], or }• If the stack is empty: return false• Else pop the top opening bracket and check if it
matches the corresponding closing bracket
• Return true if the stack is empty
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
13
�
Hierarchical CollectionsHierarchical Collections
• Tree definition• Types of Trees• Binary Expressions
• Expression Trees• Tree traversals: pre-, in-, postorder
• Examples• Generating Postfix, Parsing
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
14
�
Tree DefinitionTree Definition
• Each node has at most one predecessor• Parent
• Many Successors• Children
• Siblings• Nodes sharing the same parent (eg, D2 and D3)
D2
D1
D3
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
15
�
Tree Definition (2)Tree Definition (2)
• Topmost Node: root
• Successors• Children, Children of
Children• Also called
descendants• All nodes are
successors of root
D2
D1
D3
D4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
16
�
Tree Definition (3)Tree Definition (3)
• Leaf Nodes:• Nodes without
Successors• E.g. D3 and D4
• Frontier:• The set of all leaf
nodes
D2
D1
D3
D4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
17
�
Tree Definition (4)Tree Definition (4)
• Interior Nodes:• Nodes with at least
one successor• E.g. D1 and D2
• Ancestors:• Immediate or indirect
predecessors• E.g, D1 is an ancestor
of D2, D3, and D4
D2
D1
D3
D4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
18
�
Tree Definition (5)Tree Definition (5)
• Levels are numbered from 0• Level 0 is always the
root• This tree has 3 Levels
• Level 0: D1• Level 1: D2 and D3• Level 2: D4
D2
D1
D3
D4
Level 0
Level 2
Level 1
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
19
�
Binary TreesBinary Trees
• Binary Trees allow at most two children per Node
• Generic Trees allow any number of children per Node
D2
D1
D3
D4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
20
�
Generic TreesGeneric Trees
• Order of the Tree:• Maximum Number of
successors allowed for any given Node
• E.g., Order: 3• Generic Trees are
sometimes called General Trees
D2
D1
D3
D4
D5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
21
�
Tree ApplicationsTree Applications
• Parsing Languages• Computer Languages, Mathematical Formula• Natural Languages
• Searchable Data Structures• Databases (e.g., B-Trees)
• Heaps and Balanced Trees• Sorting and organising Data
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
22
�
ParsersParsers
• Read in Expressions• E.g., (2 + 3) * 5
• Check Syntactical Correctness• Is everything where it should be?
• Create Parse Tree• Evaluator checks semantic meaning and
processes the data in the Tree to produce meaningful output
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
23
�
Binary ExpressionsBinary Expressions
• Stored in Binary Trees: e.g. 3+5
• Numbers• Leaf Nodes
• Operators• Interior Nodes
• Operands• Contained in Subtree of the Expression
3
+
5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
24
�
Example ExpressionExample Expression
• 3 * 4 + 5
*
+
5
3 4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
25
�
Example Expression (2)Example Expression (2)
• 3 * (4 + 5)
3
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
26
�
Operator PrecedenceOperator Precedence
• 3 * (4 + 5)
• The higher the precedence, the lower in the tree!
• Overridden by parentheses!
3
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
27
�
Operator Precedence (2)Operator Precedence (2)
• 3 + 4 + 5• If operators have
equal precedence, the ones on the leftappear lower in the tree when parsed from left to right!
5
+
+
3 4
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
28
�
Evaluating an Expression TreeEvaluating an Expression Tree
• Begin at the root Node• If a number, return it, otherwise• Run the operator w/ the results of• Evaluating its left and right
subtrees, and• Return this value.
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
29
�
Evaluating ExampleEvaluating Example
• 3 * (4 + 5)
3
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
30
�
Evaluating Example (2)Evaluating Example (2)
• 3 * (4 + 5)
• * is an operator
Evaluate left and right subtrees first!
3
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
31
�
Evaluating Example (3)Evaluating Example (3)
• 3 * (4 + 5)
• 3 is a number
Return 33
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
32
�
Evaluating Example (4)Evaluating Example (4)
• 3 * (4 + 5)
• + is an operator
Evaluate left and right subtrees first!
3
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
33
�
Evaluating Example (5)Evaluating Example (5)
• 3 * (4 + 5)
• 4 is a number
Return 43
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
34
�
Evaluating Example (6)Evaluating Example (6)
• 3 * (4 + 5)
• 5 is a number
Return 53
*
+
4 5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
35
�
Evaluating Example (7)Evaluating Example (7)
• 3 * (4 + 5)
• Add subtree results
Return 4 + 5 = 93
*
+
4 5
9
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
36
�
Evaluating Example (8)Evaluating Example (8)
• 3 * (4 + 5)
• Multiply subtreeresults
Return 3 * 9 = 27
3
*
+
4 5
9
27
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
37
�
Evaluate PseudocodeEvaluate Pseudocode
evaluate(node){
if node is a numberreturn number;
else{left = evaluate(node.left);right = evaluate(node.right);return compute(node, left, right);
}}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
38
�
Binary Tree TraversalsBinary Tree Traversals
• Preorder• Visit node, then go left, then go right
• Inorder• Go left, then visit node then go right
• Postorder: Depth First• Go left, then go right, then visit node
• Breadth First• Level 0, then Level 1, then Level 2, etc.
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
39
�
Binary Tree Traversals (2)Binary Tree Traversals (2)
• Preorder, Inorder, and Postorder• Correspond with Prefix, Infix, and Postfix
Notations of an Expression• Infix: 3 + 5• Prefix = Polish Notation (PN) : +(3,5)• Postfix = Reverse Polish Notation (RPN) : 3 5 +
• Use the Same Generic Recursive Algorithm!
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
40
�
Prefix PseudocodePrefix Pseudocode
String prefix(node){
if (node == NULL)return ””;
elsereturn node +
prefix(node.left) +prefix (node.right);
}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
41
�
Infix PseudocodeInfix Pseudocode
String infix(node){
if (node == NULL)return ””;
elsereturn infix(node.left) +
node +infix (node.right);
}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
42
�
Postfix PseudocodePostfix Pseudocode
String postfix(node){
if (node == NULL)return ””;
elsereturn postfix(node.left) +
postfix (node.right) +node;
}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
43
�
A Binary Tree StructureA Binary Tree Structure
struct BTNode{
protected:BTNode *left; // left childBTNode *right; // right child
Element_Type value; // the actual data// here go the usual access methods://
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
44
�
A Binary Tree ConstructorA Binary Tree Constructor
BTNode ( Element_Type E = 0, BTNode*L=NULL, BTNode *R=NULL) : value (E), left (
L), right (R) {}
};
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
45
�
Creating a Binary TreeCreating a Binary Tree
BTNode *test_left= new BTNode (“3”, NULL,NULL);
ORBTNode *test_left= new BTNode (“3”);
3
nil nil
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
46
�
Creating a Binary TreeCreating a Binary Tree
BTNode *test_left= new BTNode (“3”);BTNode *test_right= new BTNode (“5”);
3 5
nil nil
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
47
�
Creating a Binary TreeCreating a Binary Tree
BTNode *test_left= new BTNode (“3”);BTNode *test_right= new BTNode (“5”);BTNode *test_root= new BTNode (“+”,test_left,test_right);
3
+
5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
48
�
Creating a Binary TreeCreating a Binary Tree
BTNode *test_left= new BTNode(“3”);
BTNode *test_right= new BTNode(“5”);
BTNode *test_root= new BTNode(“+”,test_left,test_right);• Infix:3 + 5• Postfix: 3 5 +
P fi +(3 5)
3
+
5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
49
�
Grammar ParsingGrammar Parsing
• Recursive Definition, e.g Infix:Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
• Represents standard math formulas, e.g.• 3 + 4 * ( 5 - ( 6 / 7 ) )
• Can be used to create a parse tree!
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
50
�
Recursive Descent ParsingRecursive Descent Parsing
Expression(){Term();while (token == '+' ||
token == '-'){
get_token();Term();
}}
Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
51
�
Recursive Descent ParsingRecursive Descent Parsing
Term(){Factor();while (token == '*' ||
token == '/'){
get_token();Factor();
}}
Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
52
�
Recursive Descent ParsingRecursive Descent ParsingFactor(){
switch (token){case number: get_token(); break;
case '(':get_token();Expression();if (token != ')')
error(”No closing ')'");get_token();
break;
default:error(Error '%s'\n", token);
}}
Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
53
�
ReferencesReferences
• Lambert, K. A., & Osborne, M. (2004): A Framework for Program Design and Data Structures: Brooks/Cole. Chapters 8-10
• http://en.wikipedia.org/wiki/Tree_data_structure• http://en.wikipedia.org/wiki/Binary_tree• http://en.wikipedia.org/wiki/Recursive_descent_parser• http://mathworld.wolfram.com/WeightedTree.html
�
AppendixAppendix
C Language Examples
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
55
�
A Binary Tree Structure (C)A Binary Tree Structure (C)
typedef struct BinTreeNode btNode;
struct BinTreeNode{
btNode *left; /* left child */btNode *right; /* right child */
void *value; /* the actual data */};
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
56
�
A Binary Tree Constructor (C)A Binary Tree Constructor (C)
btNode *newBTNode(void *data,btNode *left, btNode *right)
{btNode *this = malloc(sizeof btNode);
this->value = data;this->left = left;this->right = right;
return this;}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
57
�
Creating a Binary Tree (C)Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);
3
NULL NULL
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
58
�
Creating a Binary Tree (C)Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);btNode *right = newBTNode(”5”, NULL, NULL);
3 5
NULL NULL
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
59
�
Creating a Binary Tree (C)Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);btNode *right = newBTNode(”5”, NULL, NULL);btNode *root = newBTNode(”+”, left, right);
3
+
5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
60
�
Creating a Binary Tree (C)Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);btNode *right = newBTNode(”5”, NULL, NULL);btNode *root = newBTNode(”+”, left, right);
• Infix: 3 + 5
• Postfix: 3 5 +
• Prefix: +(3, 5)add(3, 5)
Functional Notation
3
+
5
�
AppendixAppendix
Objective-C Language Examples
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
62
�
A Binary Tree StructureA Binary Tree Structure
@interface BTNode: NSObject;{
BTNode *left; // left childBTNode *right; // right child
id value; // the actual data}// here go the usual access methods:// -setLeft, -setRight, …@end
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
63
�
A Binary Tree ConstructorA Binary Tree Constructor
- initWithValue: v left: (BTNode *) lright: (BTNode *) r
{if (!(self = [self init])) return nil;
value = v;left = l;right = r;
return self;}
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
64
�
Creating a Binary TreeCreating a Binary Tree
BTNode *left = [[BTNode alloc] initWithValue: @”3”left: nil right: nil];
3
nil nil
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
65
�
Creating a Binary TreeCreating a Binary Tree
BTNode *left = [[BTNode alloc] initWithValue: @”3”left: nil right: nil];
BTNode *right = [[BTNode alloc] initWithValue: @”5”left: nil right: nil];
3 5
nil nil
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
66
�
Creating a Binary TreeCreating a Binary Tree
BTNode *left = [[BTNode alloc] initWithValue: @”3”left: nil right: nil];
BTNode *right = [[BTNode alloc] initWithValue: @”5”left: nil right: nil];
BTNode *root = [[BTNode alloc]initWithValue: @”+”
left: leftright: right];
3
+
5
P3 Lecture #08 April 2006
Copyright © 2002-2006 René Hexel. All rights reserved.
67
�
Creating a Binary TreeCreating a Binary Tree
BTNode *left = [[BTNode alloc] initWithValue: @”3”left: nil right: nil];
BTNode *right = [[BTNode alloc] initWithValue: @”5”left: nil right: nil];
BTNode *root = [[BTNode alloc]initWithValue: @”+”
left: leftright: right];
• Infix: 3 + 5
• Postfix: 3 5 +
• Prefix: +(3, 5)add(3, 5)Functional notation
3
+
5