Data Structures and Algorithms

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

Stacks Chapter 11.
Stacks Example: Stack of plates in cafeteria.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
CMPT 225 Stacks.
CHAPTER 3 Stacks. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek  empty  To understand.
Topic 15 Implementing and Using Stacks
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Chapter 3 Stacks.
Topic 3 The Stack ADT.
The Stack Alexander G. Chefranov CMPE-231 Spring 2012.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Stack. Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
EC-211 DATA STRUCTURES LECTURE 8. STACK APPLICATIONS Infix, Prefix, and Postfix Expressions Example – Infix: A+B – Prefix: +AB – Postfix: AB+
Data Structures Stack Namiq Sultan 1. Data Structure Definition: Data structures is a study of different methods of organizing the data and possible operations.
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Data Structures & Algorithms
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
CHP-3 STACKS.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
Click to edit Master text styles Stacks Data Structure.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Stacks Chapter 5.
Stacks Stacks.
Revised based on textbook author’s notes.
Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Cinda Heeren / Geoffrey Tien
Algorithms and Data Structures
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Topic 15 Implementing and Using Stacks
(Part 2) Infix, Prefix & Postfix
Presentation transcript:

Data Structures and Algorithms Stack Instructor: Quratulain

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

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

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

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

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

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

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

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

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

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

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

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

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

Stack Application Run time Stack procedures Postfix Calculator Interpret infix with precedence CSE 246 Data Structures and Algorithms Quratulain

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

Arithmetic Expression Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions. CSE 246 Data Structures and Algorithms Quratulain

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

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

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

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

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

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

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

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

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

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 ) / ( 4 - 2.5 ) ) 0 0 1 2 3 4 3 4 3 2 1 2 1 0 CSE 246 Data Structures and Algorithms Quratulain

Again problem ) A + B ( - C -1 0 -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

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

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

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

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

CSE 246 Data Structures and Algorithms Quratulain

CSE 246 Data Structures and Algorithms Quratulain

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