Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithms

Similar presentations


Presentation on theme: "Data Structures and Algorithms"— Presentation transcript:

1 Data Structures and Algorithms
Stack Instructor: Quratulain

2 Stack Last-in, First-out (LIFO) structure
Given 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 Operations Elements are added to and removed from one designated end called the top. Basic Operations Push(), add element into the stack pop(), remove & return topmost element Other Operation Empty() Top() Size() 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
// in the code of main function that uses // the stack … stackList.push( 95 ); public class ArrayStack { // ... public boolean empty() { return (top == -1); } public void push(int entry) if (top < MAX-1) stackList[++top] = entry; // ... top 4 4 1 4 32 7 95 ... CSE 246 Data Structures and Algorithms Quratulain

6 ArrayStack class, continued
// in the code that uses // the stack … int x = stackList.pop(); public class ArrayStack { // ... public int pop() throws Exception if ( empty() ) throw new Exception(); else return stackList[top--]; } // x gets 95, // slot 4 is now free Note: Store[4] still contains 95, but it’s now considered “free”. top 5 4 12 24 37 17 95 ... CSE 246 Data Structures and Algorithms Quratulain

7 Using the Stack try { ArrayStack st = new ArrayStack();
st.push( 1 ); st.push( 3 ); st.push( 2 ); System.out.println( st.pop() ); st.push( 5 ); } 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 specified Consequences stack may fill up (when top == MAX) memory is wasted if actual stack consumption is below maximum Need a more “dynamic” implementation The 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 Class top 5 1 3 2 null public class LinkedStack {
StackNode top; public LinkedStack() top = null; } public boolean empty() return (top == null); // ... top 5 1 3 2 null 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; } // … } // in the code // that uses the // stack Mystack.push( 7 ); temp top X 1 2 null 7 5 3 CSE 246 Data Structures and Algorithms Quratulain

13 Pop Operation using a List
public class LinkedStack { // ... public int pop() throws Exception { if ( empty() ) { throw new Exception(); } else int temp = top.getData(); top = top.getNext(); return temp; // in the code // that uses the // stack int x = MyStack.pop(); null 5 1 3 2 7 temp Garbage Collected top 7 X CSE 246 Data Structures and Algorithms Quratulain

14 Stack using Linked List
The 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 Application Run time Stack procedures Postfix Calculator
Interpret infix with precedence CSE 246 Data Structures and Algorithms Quratulain

16 Stack Application 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. 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 Expressions
Infix Expressions An expression in which every binary operation appears between its operands Example: (i) a+b “+” is a binary operation and a and b are its operands (ii) (a+b)*c Prefix Expressions An expression in which operator comes before its operands (i) a+b = +ab (ii) (a+b)*c = *+abc (iii) a+(b*c) =+a*bc Postfix Expressions An expression in which operator comes after its operands (i) a+b = ab+ (ii) (a+b)*c = ab+c* (iii) a+(b*c) = abc*+ CSE 246 Data Structures and Algorithms Quratulain

19 Infix notation Infix 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 implications
Calculations 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 Push operand , Push operand Addition , Push operand * Multiplication , Push operand Addition * 3 + CSE 246 Data Structures and Algorithms Quratulain

24 Infix to Postfix conversion Algorithm
Opstk = 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
7 – ((X * ((X+Y) / (J-3)) + Y) / (4-2.5)) Ensure parenthesis nested correctly There are an equal number of right and left parentheses. 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 parenthesis
The 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 ) / ( ) ) 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 stack While (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 validate
Pushing 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 Java
The 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. CSE 246 Data Structures and Algorithms Quratulain

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

33 CSE 246 Data Structures and Algorithms Quratulain

34 CSE 246 Data Structures and Algorithms Quratulain

35 Implementing a Stack with a Generic Linked List
Left as homework CSE 246 Data Structures and Algorithms Quratulain


Download ppt "Data Structures and Algorithms"

Similar presentations


Ads by Google