Data Structures and Algorithms Stack Instructor: Quratulain.
-
Upload
abigayle-glenn -
Category
Documents
-
view
221 -
download
0
Transcript of Data Structures and Algorithms Stack Instructor: Quratulain.
2
StackLast-in, First-out (LIFO) structureGiven a stack S = (a0, a1, … an-1, an),
we say that a0 is the bottom element, an is the top element if they are added in the order of a0,a1, .. and an
Sample uses◦“Back” button of a browse◦“Undo” operation◦function/method calls PEZ® candy dispenser
CSE 246 Data Structures and Algorithms Quratulain
3
Stack OperationsElements are added to and
removed from one designated end called the top.
Basic Operations◦Push(), add element into the stack◦pop(), remove & return topmost
elementOther Operation
◦Empty()◦Top()◦Size()CSE 246 Data Structures and Algorithms Quratulain
CSE 246 Data Structures and Algorithms Quratulain
4
Array Implementation of a Stack
public class ArrayStack { int stackList[]; int top; static final int MAX = 100;
public ArrayStack() { stackList = new int[MAX]; top = -1; } // ...}
3 top
1 4 32 7 ...
CSE 246 Data Structures and Algorithms Quratulain
5
ArrayStack class, continued
public class ArrayStack { // ... public boolean empty() { return (top == -1); } public void push(int entry) { if (top < MAX-1) stackList[++top] = entry; } // ...}
...
4top
1 4 32 7
// in the code of main function that uses
// the stack …
stackList.push( 95 );
95
4
CSE 246 Data Structures and Algorithms Quratulain
6
ArrayStack class, continued
public class ArrayStack
{
// ...
public int pop()
throws Exception
{
if ( empty() )
throw new Exception();
else
return stackList[top--];
}
}
...
5top
12 24 37 17 95
4
// in the code that uses// the stack …
int x = stackList.pop();
// x gets 95, // slot 4 is now free
Note:Store[4] still contains 95, but it’s nowconsidered “free”.
CSE 246 Data Structures and Algorithms Quratulain
7
Using the Stacktry { ArrayStack st = new ArrayStack(); st.push( 1 ); st.push( 3 ); st.push( 2 ); System.out.println( st.pop() ); st.push( 5 ); System.out.println( st.pop() ); System.out.println( st.pop() );}catch ( Exception e ) { System.out.println( “pop() on empty stack” );
}
CSE 246 Data Structures and Algorithms Quratulain
8
Problems with Array Implementation
MAX (size of array) needs to be specifiedConsequences
◦stack may fill up (when top == MAX)◦memory is wasted if actual stack consumption
is below maximumNeed a more “dynamic” implementationThe array implementation of a stack is
simple and efficient for known size of list.Time complexity of all stack operations is
O(1).
CSE 246 Data Structures and Algorithms Quratulain
9
Linked List Implementation use a singly linked list to implement the stack ADT. Stack as a sequence of nodes
public class StackNode
{
object info;
StackNode next;
public StackNode(){}
public StackNode(Object j, StackNode p)
{info = j; next = p;
}
}
CSE 246 Data Structures and Algorithms Quratulain
10
Linked List as a Data Structure
Operations on a linked list◦insert a node somewhere in the list◦get next node◦delete a node from the list
Linked List Implementation of a Stack:◦It is an example of a data structure
implemented through another data structure
CSE 246 Data Structures and Algorithms Quratulain
11
LinkedStack Classpublic class LinkedStack
{
StackNode top;
public LinkedStack()
{
top = null;
}
public boolean empty()
{
return (top == null);
}
// ...
}
null5 1 3 2
top
CSE 246 Data Structures and Algorithms Quratulain
12
Push Operation using a List
public class LinkedStack { // ... public void push( int entry ) { StackNode temp = new StackNode(); temp.setData( entry ); temp.setNext( top ); top = temp; } // … }
null5 1 3 2
top
// in the code// that uses the// stack
Mystack.push( 7 );
7
temp
X
CSE 246 Data Structures and Algorithms Quratulain
13
Pop Operation using a Listpublic class LinkedStack
{
// ...
public int pop() throws Exception
{ if ( empty() )
{ throw new Exception();
}
else
{
int temp = top.getData();
top = top.getNext();
return temp;
}
}
}
top
X
// in the code// that uses the// stack
int x = MyStack.pop();
7
null5 1 3 27
temp
GarbageCollected
CSE 246 Data Structures and Algorithms Quratulain
14
Stack using Linked ListThe time complexity of all
operations is O(1) except destructor, which takes O(n) time.
For applications in which the maximum stack size is known ahead of time, an array is suitable
If the maximum stack size is not known beforehand, we can use a linked list
CSE 246 Data Structures and Algorithms Quratulain
15
Stack ApplicationRun time Stack proceduresPostfix CalculatorInterpret infix with precedence
CSE 246 Data Structures and Algorithms Quratulain
16
Almost invariably, programs compiled from modern high level languages (even C!) make use of a stack frame for the working memory of each procedure or function invocation.
When any procedure or function is called, a number of words - the stack frame - is pushed onto a program stack.
Stack Application
CSE 246 Data Structures and Algorithms Quratulain
17
Arithmetic Expression Infix, Postfix and Prefix notations
are three different but equivalent ways of writing expressions.
CSE 246 Data Structures and Algorithms Quratulain
18
Arithmetic ExpressionsInfix ExpressionsAn expression in which every binary operation appears between its
operandsExample: (i) a+b “+” is a binary operation and a and b are its operands(ii) (a+b)*c
Prefix ExpressionsAn expression in which operator comes before its operandsExample: (i) a+b = +ab(ii) (a+b)*c = *+abc(iii) a+(b*c) =+a*bc
Postfix ExpressionsAn expression in which operator comes after its operandsExample: (i) a+b = ab+(ii) (a+b)*c = ab+c*(iii) a+(b*c) = abc*+
CSE 246 Data Structures and Algorithms Quratulain
19
Infix notationInfix notation: A * ( B + C ) / D Infix notation needs extra
information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules.
CSE 246 Data Structures and Algorithms Quratulain
20
Postfix notation The order of evaluation of
operators is always left-to-right, and brackets cannot be used to change this order.
Operators act on values immediately to the left of them.
RPN has the advantage of being extremely easy, and therefore fast, for a computer to analyze.
CSE 246 Data Structures and Algorithms Quratulain
21
Postfix In the 1920's, Jan Lukasiewicz developed a
formal logic system which allowed mathematical expressions to be specified without parentheses by placing the operators before (prefix notation) or after (postfix notation) the operands.
postfix notation for a calculator keyboard.computer scientists realized that RPN or
postfix notation was very efficient for computer math.
As a postfix expression is scanned from left to right, operands are simply placed into a last-in, first-out (LIFO) stack and operators may be immediately applied to the operands at the bottom of the stack.
Another advantage is consistency between machines.
CSE 246 Data Structures and Algorithms Quratulain
22
Practical implicationsCalculations proceed from left to right There are no brackets or parentheses,
as they are unnecessary. Operands precede operator. They are
removed as the operation is evaluated.
When an operation is made, the result becomes an operand itself (for later operators)
There is no hidden state. No need to wonder if you hit an operator or not.
CSE 246 Data Structures and Algorithms Quratulain
23
Example The calculation: ((1 + 2) * 4) + 3 can be written
down like this in RPN:
The expression is evaluated in the following way (the Stack is displayed after Operation has taken place):
Input Stack Operation 1 1 Push operand 2 1, 2 Push operand + 3 Addition 4 3, 4 Push operand * 12 Multiplication 3 12,3 Push operand + 15 Addition
1 2 + 4 * 3 +
CSE 246 Data Structures and Algorithms Quratulain
24
Infix to Postfix conversion AlgorithmOpstk = the empty stack while(not end of input) { symb=next input char; if (symbol is operand) add symb in postfix string else { while(!empty(opstk)&& prcd(stacktop(opstk), symb)) { topsymb=pop(opstk);
add topsymb to postfix string; } }while(!empty(opstk)) {topsymb=pop(opstk);add topsymb to postfix string;}
CSE 246 Data Structures and Algorithms Quratulain
25
Algorithm for postfix evalution
Opndstk = the emty stack;While (not end of input)
{Symb = next input character;If (symb is an operand)Push(opndstk,symb);Else
{Opnd2=pop(opndstk);Opnd1=pop(opndstk);Value = result of applying symb to opnd1 and opnd2;Push(opndstk, value);}
}Return (pop(opndstk));
CSE 246 Data Structures and Algorithms Quratulain
26
A Mathematical expression
A mathematical expression:7 – ((X * ((X+Y) / (J-3)) + Y) / (4-2.5))Ensure parenthesis nested correctly1. There are an equal number of right and
left parentheses.2. Every right parenthesis is preceded by
a matching left parenthesis.E.G ((A+B) or A+B( …. Violate condition 1)A+B(-C or (A+B))-(C+D … Violate
condition 2
CSE 246 Data Structures and Algorithms Quratulain
27
Solution for parenthesisThe parenthesis count at the end of the
expression is 0. this implies that no scope have been left open or that exactly as many right parentheses as left parentheses have been found.
The parenthesis count at each point in the expression is nonnegative. This implies that no right parenthesis is encountered for which a matching left parenthesis had not previosly been encountered.
7 – ( ( X * ( ( X + Y ) / ( J – 3 ) ) + Y ) / ( 4 - 2.5 ) )
0 0 1 2 3 4 3 4 3 2 1 2 1 0
CSE 246 Data Structures and Algorithms Quratulain
28
Again problem
) A + B ( - C-1 0
There are three different type of scope delimiters exits {}, [], ()
The stack may be used to keep track of the types of scopes encountered
CSE 246 Data Structures and Algorithms Quratulain
29
Algorithm for parenthesis Validation
Valid = true;S= the empty stackWhile (we have not read the entire string){Read the next symbol (symb) of the string;If (symb == ‘(‘ || symb == ‘{‘ || symb == ‘[‘)Push (s, symb);If (symb == ‘)‘ || symb == ‘}‘ || symb == ‘]‘) if (empty(s)) valid =false; else { i=pop(s); if (i is not the matching operand of symb) valid=false;If (valid)Print(“valid String”);Else Print(“Not valid String”);
CSE 246 Data Structures and Algorithms Quratulain
30
Arithmetic Expression validatePushing an item on to stack
correspond to opening a scope, and popping an item from the stack corresponds to closing a scope.
When the stack is empty and scope ender encountered, so the parenthesis pattern is invalid.
CSE 246 Data Structures and Algorithms Quratulain
31
A Stack Interface in JavaThe stack data structure is included as a
"built-in" class in the java.util package of Java.
it is instructive to learn how to design and implement a stack "from scratch.“
Implementing an abstract data type in Java involves two steps◦Define interface ◦Define exceptions for any error conditions that
can arise.◦Provide a concrete class that implements the
methods of the interface associated with that ADT.
32
Stack interface
public interface Stack <E> { public int size(); public boolean isEmpty(); public E top() throws
EmptyStackException; public void push( E element); public E pop() throws
EmptyStackException; }CSE 246 Data Structures and Algorithms Quratulain