Upcoming SlideShare
×

# Lecture2

665 views
593 views

Published on

Published in: Education, Technology
2 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
665
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
23
0
Likes
2
Embeds 0
No embeds

No notes for slide

### Lecture2

1. 1. Part-B1 Stacks
2. 2. Abstract Data Types (ADTs) <ul><li>An abstract data type (ADT) is an abstraction of a data structure </li></ul><ul><li>An ADT specifies: </li></ul><ul><ul><li>Data stored </li></ul></ul><ul><ul><li>Operations on the data </li></ul></ul><ul><ul><li>Error conditions associated with operations </li></ul></ul><ul><li>Example: ADT modeling a students record </li></ul><ul><ul><li>The data stored are </li></ul></ul><ul><ul><ul><li>Student name, id No., as1, as2,as3, exam </li></ul></ul></ul><ul><ul><li>The operations supported are </li></ul></ul><ul><ul><ul><li>int averageAs (as1,as2,as3) </li></ul></ul></ul><ul><ul><ul><li>Int finalMark (as1, as2,as3, exam) ) </li></ul></ul></ul><ul><ul><li>Error conditions: </li></ul></ul><ul><ul><ul><li>Calculate the final mark for absent student </li></ul></ul></ul>
3. 3. The Stack ADT (§4.2) <ul><li>The Stack ADT stores arbitrary objects </li></ul><ul><li>Insertions and deletions follow the last-in first-out scheme </li></ul><ul><li>Think of a spring-loaded plate dispenser </li></ul><ul><li>Main stack operations: </li></ul><ul><ul><li>push (object): inserts an element </li></ul></ul><ul><ul><li>object pop (): removes and returns the last inserted element </li></ul></ul><ul><li>Auxiliary stack operations: </li></ul><ul><ul><li>object top (): returns the last inserted element without removing it </li></ul></ul><ul><ul><li>integer size (): returns the number of elements stored </li></ul></ul><ul><ul><li>boolean isEmpty (): indicates whether no elements are stored </li></ul></ul>
4. 4. Stack Interface in Java <ul><li>Java interface corresponding to our Stack ADT </li></ul><ul><li>Requires the definition of class EmptyStackException </li></ul>public interface Stack { public int size() ; public boolean isEmpty() ; public Object top() throws EmptyStackException ; public void push(Object o) ; public Object pop() throws EmptyStackException ; }
5. 5. Exceptions <ul><li>Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception </li></ul><ul><li>Exceptions are said to be “thrown” by an operation that cannot be executed </li></ul><ul><li>In the Stack ADT, operations pop and top cannot be performed if the stack is empty </li></ul><ul><li>Attempting the execution of pop or top on an empty stack throws an EmptyStackException </li></ul>
6. 6. Applications of Stacks <ul><li>Direct applications </li></ul><ul><ul><li>Undo sequence in a text editor </li></ul></ul><ul><ul><li>Chain of method calls in the Java Virtual Machine </li></ul></ul><ul><li>Indirect applications </li></ul><ul><ul><li>Auxiliary data structure for algorithms </li></ul></ul><ul><ul><li>Component of other data structures </li></ul></ul>
7. 7. Array-based Stack (Implementation) <ul><li>A simple way of implementing the Stack ADT uses an array </li></ul><ul><li>We add elements from left to right </li></ul><ul><li>A variable t keeps track of the index of the top element </li></ul>S 0 1 2 t … Algorithm size () return t + 1 Algorithm pop () if isEmpty () then throw EmptyStackException else t  t  1 return S [ t + 1]
8. 8. Array-based Stack (cont.) <ul><li>The array storing the stack elements may become full </li></ul><ul><li>A push operation will then throw a FullStackException </li></ul><ul><ul><li>Limitation of the array-based implementation </li></ul></ul><ul><ul><li>Not intrinsic to the Stack ADT </li></ul></ul>Algorithm push ( o ) if t = S.length  1 then throw FullStackException else t  t + 1 S [ t ]  o S 0 1 2 t …
9. 9. Array-based Stack (Cont.) <ul><li>A Stack might be empty </li></ul><ul><li>top returns the element at the top of the Stack, but does not remove the top element. When the Stack is empty, an error occurs. </li></ul>S 0 1 2 t … Algorithm isEmpty() if t<0 then return true else return false Algorithm top () if isEmpty () then throw EmptyStackException return S [ t ]
10. 10. Performance and Limitations for array-based Stack <ul><li>Performance </li></ul><ul><ul><li>Let n be the number of elements in the stack </li></ul></ul><ul><ul><li>The space used is O ( n ) </li></ul></ul><ul><ul><li>Each operation runs in time O (1) </li></ul></ul><ul><li>Limitations </li></ul><ul><ul><li>The maximum size of the stack must be defined a priori and cannot be changed </li></ul></ul><ul><ul><li>Trying to push a new element into a full stack causes an implementation-specific exception </li></ul></ul>
11. 11. Array-based Stack in Java public class ArrayStack implements Stack { // holds the stack elements private Object S[ ]; // index to top element private int top = -1; // constructor public ArrayStack(int capacity) { S = new Object[capacity]); }
12. 12. Array-based Stack in Java public Object pop() throws EmptyStackException { if isEmpty() throw new EmptyStackException (“ Empty stack: cannot pop ”); Object temp = S[top]; // facilitates garbage collection S[top] = null ; top = top – 1; return temp; } public int size() { return (top + 1);
13. 13. Array-based Stack in Java public boolean isEmpty() { return (top < 0); } public void push(Object obj) throws FullStackException { if (size() == capacity) throw new FullStackException(&quot;Stack overflow.&quot;); S[++top] = obj; } public Object top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(&quot;Stack is empty.&quot;); return S[top]; }
14. 14. Parentheses Matching <ul><li>An expression, i.e.,[(2+3)*x+5]*2. </li></ul><ul><li>Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” </li></ul><ul><ul><li>correct: ( )(( )) { ([( )]) } </li></ul></ul><ul><ul><li>correct: ((( )(( )) { ([( )]) } </li></ul></ul><ul><ul><li>incorrect: )(( )) { ([( )]) } </li></ul></ul><ul><ul><li>incorrect: ( { [ ]) } </li></ul></ul><ul><ul><li>incorrect: ( </li></ul></ul>
15. 15. Parentheses Matching Algorithm <ul><li>Algorithm ParenMatch ( X , n ) : </li></ul><ul><li>Input: An array X of n tokens, each of which is either a grouping symbol, a </li></ul><ul><li>variable, an arithmetic operator, or a number </li></ul><ul><li>Output: true if and only if all the grouping symbols in X match </li></ul><ul><li>Let S be an empty stack </li></ul><ul><li>for i = 0 to n - 1 do </li></ul><ul><li>if X [ i ] is an opening grouping symbol then </li></ul><ul><li>S . push ( X [ i ] ) </li></ul><ul><li>else if X [ i ] is a closing grouping symbol then </li></ul><ul><li>if S . isEmpty () then </li></ul><ul><li>return false { nothing to match with } </li></ul><ul><li>if S . pop () does not match the type of X [ i ] then </li></ul><ul><li>return false { wrong type } </li></ul><ul><li>if S . isEmpty () then </li></ul><ul><li>return true { every symbol matched } </li></ul><ul><li>else </li></ul><ul><li>return false { some symbols were never matched } </li></ul>
16. 16. Parentheses Matching Example 1 <ul><li>Input: () (() [()]) </li></ul>([ Push [ [ 5 ( Pop ( Test if ( and X[i] match? YES ) 4 (( Push ( ( 3 ( Push ( ( 2 Pop ( Test if ( and X[i] match? YES ) 1 ( Push ( ( 0 Output Stack Operation X[i] i
17. 17. Parentheses Matching Example 1 <ul><li>Input: () (() [()]) </li></ul>Pop ( Test if ( and X[i] match? YES ) 9 TRUE Test if stack is Empty? YES ( Pop [ Test if [ and X[i] match? YES ] 8 ([ Pop ( Test if ( and X[i] match? YES ) 7 ([( Push ( ( 6 Output Stack Operation X[i] i
18. 18. Parentheses Matching Example 2 <ul><li>Input: ( () [] ]() </li></ul>FASLE Pop ( Test if ( and X[i] match ? NO ] 5 ( Pop [ Test if [ and X[i] match? YES ] 4 ([ Push [ [ 3 ( Pop ( Test if ( and X[i] match? YES ) 2 (( Push ( ( 1 ( Push ( ( 0 Output Stack Operation X[i] i
19. 19. Computing Spans (not in book) <ul><li>We show how to use a stack as an auxiliary data structure in an algorithm </li></ul><ul><li>Given an array X , the span S [ i ] of X [ i ] is the maximum number of consecutive elements X [ j ] immediately preceding X [ i ] and such that X [ j ]  X [ j+1 ] </li></ul><ul><li>Spans have applications to financial analysis </li></ul><ul><ul><li>E.g., stock at 52-week high </li></ul></ul>X S 1 3 2 1 1 2 5 4 3 6
20. 20. Quadratic Algorithm Algorithm spans1 ( X, n ) Input array X of n integers Output array S of spans of X # S  new array of n integers n for i  0 to n  1 do n s  1 n while s  i  X [ i  s ]  X [ i -s+1 ] 1  2  …  ( n  1) s  s  1 1  2  …  ( n  1) S [ i ]  s n return S 1 X[]= 1,2,3, …, n-1, n. <ul><li>Algorithm spans1 runs in O ( n 2 ) time </li></ul>
21. 21. Computing Spans with a Stack <ul><li>We push the n elements in the stack </li></ul><ul><li>We sacn the elements in the stack in the reverse order. </li></ul><ul><ul><li>We find the last element x[j] with x[j]<=x[i] and x[j-1]>x[i] and set s[i]=i-j+1. </li></ul></ul><ul><ul><li>If no such a j exists, s[i]=i+1. </li></ul></ul><ul><li>Compute the s[i] for the remaining i’s as follows: </li></ul><ul><ul><li>for (i=n-2; i>=0; i--) </li></ul></ul><ul><ul><li>if (s[i+1]>1 & s[i]==0) then </li></ul></ul><ul><ul><li>s[i]=s[i+1]-1 </li></ul></ul>
22. 22. Example: <ul><li>i= 0, 1, 2, 3, 4, 5, 6, 7 </li></ul><ul><li>X[i]= 6, 3, 4, 1, 2, 3, 5, 4 </li></ul><ul><li>S[i]= 1, 1, 2, 1, 2, 3, 4, 1. </li></ul><ul><li>4 </li></ul><ul><li>5 5 </li></ul><ul><li>3 3 </li></ul><ul><li>2 2 </li></ul><ul><li>1 1 </li></ul><ul><li>4 4 4 </li></ul><ul><li>3 3 3 </li></ul><ul><li>6 6 6 6 </li></ul><ul><li>Stack Stack Stack Stack Stack </li></ul>
23. 23. Linear Algorithm Algorithm spans2 ( X, n ) # S  new array of n integers n A  new empty stack 1 for i  0 to n  1 do A.push(i) n i=n-1 ; j=n-1 ; 1 while (i<=0) do while (  A . isEmpty ()  X [ A.top ()]  X [ j ] ) do n j  A.pop () n if A . isEmpty () then n S [ i ]  i  1 1 else S [ i ]  i  j +1 n i=j-1; n return S 1 <ul><li>Each index of the array </li></ul><ul><ul><li>Is pushed into the stack exactly one </li></ul></ul><ul><ul><li>Is popped from the stack at most once </li></ul></ul><ul><li>The statements in the two while loops are executed at most n times </li></ul><ul><li>Algorithm spans2 runs in O ( n ) time </li></ul><ul><li>for (i=n-2; i>=0; i--) </li></ul><ul><ul><li>if (s[i+1]>1 & s[i]==0) then s[i]=s[i+1]-1 </li></ul></ul>
24. 24. Summary of Stack <ul><li>Understand the definition of Stack ( basic ) </li></ul><ul><li>Applications </li></ul><ul><ul><li>Parentheses ( moderate ) </li></ul></ul><ul><ul><li>Computing Spans ( not required ) </li></ul></ul><ul><li>Implementation of Stack is not required. </li></ul><ul><li>You should be able to use stack to write programs to solve problems </li></ul>
25. 25. Week 3: Tutorial Arrangement <ul><li>Week 3 Tutorial (Feb. 6, 2006, 6:30p.m. – 7:20p.m) will be in MMW2478 (CS lab, second floor, Lift 18, on the left hand side after you go through the tunnel.) </li></ul>City Uni. Lift 18 Tunnel connecting city U and Festival Walk
26. 26. Remarks <ul><li>Emphasize the concept of ADT. </li></ul><ul><li>More examples about ADT </li></ul><ul><li>Delete the Span application examples. </li></ul><ul><li>Add Queue part (perhaps to week 3) </li></ul><ul><li>Teach slowly. </li></ul>