stacks, queues and hierarchical collections · queues and stacks •linear collections •can be...
TRANSCRIPT
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 1
�
Stacks, Queues and HierarchicalCollections
2501ICTNathan
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
2
�
Contents
• Linked Data Structures Revisited• Stacks• Queues
• Trees• Binary Trees• Generic Trees
• Implementations
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 2
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
3
�
Queues and Stacks
• Linear Collections• Can be implemented in different ways, e.g.
• Arrays• Linked Lists
• Are often used in Operating Systemsand run time environments• Function/Method calling Stacks• Process priority Queues
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
4
�
Queues
• 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
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 3
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
5
�
Queues 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
6
�
Priority 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 operation¬ Useful if number of different priorities is small
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 4
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
7
�
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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
8
�
Queue Applications
• First-Come-First Serve Algorithms→ OS Process Scheduling→ Event Handling→ Modelling and Simulation of Real-
World Processes• E.g. checkout queue in a supermarket
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
9
�
Stacks
• 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
10
�
Array Implementation
• Index: i = 0;• Push: stack[i++] = element;
• Pop: element = stack[--i];
• Peek: element = stack[i-1];• “Sneak preview,” without changing i
• Watch Preconditions!
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 6
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
11
�
Stack Example
• Parsing Matching Parentheses• 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
12
�
Matching () 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
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 7
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
13
�
Hierarchical Collections
• Tree definition• Types of Trees• Binary Expressions
• Expression Trees• Tree traversals: pre-, in-, postorder
• Examples• Generating Postfix, Parsing
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
14
�
Tree Definition
• Each node has at most onepredecessor• Parent
• Many Successors• Children
• Siblings• Nodes sharing the same parent (eg, D2 and D3)
D2
D1
D3
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 8
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
15
�
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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
16
�
Tree Definition (3)
• Leaf Nodes:• Nodes without
Successors• E.g. D3 and D4
• Frontier:• The set of all leaf nodes
D2
D1
D3
D4
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 9
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
17
�
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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
18
�
Tree Definition (5)
• Levels arenumbered 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
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 10
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
19
�
Binary Trees
• Binary Trees allowat most twochildren per Node
• Generic Treesallow any numberof children perNode
D2
D1
D3
D4
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
20
�
Generic Trees
• Order of the Tree:• Maximum Number of
successors allowed forany given Node
• E.g., Order: 3• Generic Trees are
sometimes calledGeneral Trees
D2
D1
D3
D4
D5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 11
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
21
�
Tree 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
22
�
Parsers
• 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
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 12
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
23
�
Binary 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
24
�
Example Expression
• 3 * 4 + 5
*
+
5
3 4
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 13
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
25
�
Example Expression (2)
• 3 * (4 + 5)
3
*
+
4 5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
26
�
Operator Precedence
• 3 * (4 + 5)
• The higher theprecedence, the lowerin the tree!
• Overridden byparentheses!
3
*
+
4 5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 14
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
27
�
Operator Precedence (2)
• 3 + 4 + 5• If operators have equal
precedence, the oneson the left appearlower in the tree whenparsed from left toright!
5
+
+
3 4
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
28
�
Evaluating 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.
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 15
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
29
�
Evaluating Example
• 3 * (4 + 5)
3
*
+
4 5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
30
�
Evaluating Example (2)
• 3 * (4 + 5)
• * is an operator
¬Evaluate left and rightsubtrees first!
3
*
+
4 5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 16
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
31
�
Evaluating Example (3)
• 3 * (4 + 5)
• 3 is a number
¬Return 33
*
+
4 5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
32
�
Evaluating Example (4)
• 3 * (4 + 5)
• + is an operator
¬Evaluate left and rightsubtrees first!
3
*
+
4 5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 17
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
33
�
Evaluating Example (5)
• 3 * (4 + 5)
• 4 is a number
¬Return 43
*
+
4 5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
34
�
Evaluating Example (6)
• 3 * (4 + 5)
• 5 is a number
¬Return 53
*
+
4 5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 18
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
35
�
Evaluating Example (7)
• 3 * (4 + 5)
• Add subtree results
¬Return 4 + 5 = 93
*
+
4 5
9
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
36
�
Evaluating Example (8)
• 3 * (4 + 5)
• Multiply subtreeresults
¬Return 3 * 9 = 27
3
*
+
4 5
9
27
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 19
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
37
�
Evaluate Pseudocode
evaluate(node){ if node is a number return number; else { left = evaluate(node.left); right = evaluate(node.right); return compute(node, left, right); }}
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
38
�
Binary 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.
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 20
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
39
�
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 RecursiveAlgorithm!
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
40
�
Prefix Pseudocode
String prefix(node){ if (node == NULL) return ””; else return node + prefix(node.left) + prefix (node.right);}
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 21
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
41
�
Infix Pseudocode
String infix(node){ if (node == NULL) return ””; else return infix(node.left) + node + infix (node.right);}
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
42
�
Postfix Pseudocode
String postfix(node){ if (node == NULL) return ””; else return postfix(node.left) + postfix (node.right) + node;}
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 22
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
43
�
A Binary Tree Structure
@interface BTNode: NSObject;{ BTNode *left; // left child BTNode *right; // right child
id value; // the actual data}// here go the usual access methods:// -setLeft, -setRight, …@end
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
44
�
A Binary Tree Constructor
- initWithValue: v left: (BTNode *) lright: (BTNode *) r
{if (![self init]) return nil;
value = v;left = l;right = r;
return self;}
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 23
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
45
�
Creating a Binary Tree
BTNode *left = [[BTNode alloc] initWithValue: @”3” left: nil right: nil];
3
nil nil
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
46
�
Creating 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
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 24
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
47
�
Creating 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: left right: right];
3
+
5
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
48
�
Creating 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: left right: right];
• Infix: 3 + 5
• Postfix: 3 5 +
• Prefix: +(3, 5)add(3, 5)Functional notation
3
+
5
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 25
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
49
�
Grammar 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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
50
�
Recursive Descent Parsing
Expression(){ Term(); while (token == '+' || token == '-') { get_token(); Term(); }}
Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 26
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
51
�
Recursive Descent Parsing
Term(){ Factor(); while (token == '*' || token == '/') { get_token(); Factor(); }}
Expression = Term { + | - Term }Term = Factor { * | / Factor }Factor = number | ( Expression )
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
52
�
Recursive Descent Parsing
Factor(){ 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 )
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 27
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
53
�
References
• Lambert, K. A., & Osborne, M. (2004): A Framework forProgram 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• Week 6 example code: SimpleTree.zip
�
Appendix
C Language Examples
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 28
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
55
�
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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
56
�
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;}
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 29
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
57
�
Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);
3
NULL NULL
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
58
�
Creating a Binary Tree (C)
btNode *left = newBTNode(”3”, NULL, NULL);btNode *right = newBTNode(”5”, NULL, NULL);
3 5
NULL NULL
Programming III April 2007
Copyright © 2002-2007 by René Hexel. Allrights reserved. 30
P3 Lecture April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
59
�
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 April2007
Copyright © 2002-2007 René Hexel.All rights reserved.
60
�
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