CSE 214 Computer Science II Stack

Size: px
Start display at page:

Download "CSE 214 Computer Science II Stack"

Transcription

1 CSE 214 Computer Science II Stack Spring 2018 Stony Brook University Instructor: Shebuti Rayana

2 Random and Sequential Access Random Access Data Structures Example: array each element can be accessed directly and in constant time typical illustration of random access is a book - each page of the book can be open independently of others random access is critical to many algorithms, for example binary search. Sequential Access Data Structures Example: linked list each element can be accessed only in particular order typical illustration of sequential access is a roll of paper or tape - all prior material must be unrolled in order to get to data you want. Shebuti Rayana (CS, Stony Brook University) 2

3 Random and Sequential Access Shebuti Rayana (CS, Stony Brook University) 3

4 Limited Access Data Structures A subcase of sequential data structures called limited access data structures: Stacks and Queues stack - elements can be added and removed from the stack only at the top queue - elements can be added at the back and can be removed only from the front They are limited access because access is restricted only to certain terminal positions. Shebuti Rayana (CS, Stony Brook University) 4

5 Stack In stacks only two operations are allowed: push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you have to remove the top book first, also if you want to add new book, you have to add it on the top. Shebuti Rayana (CS, Stony Brook University) 5

6 Stack: Applications The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack. Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack. Programming language processing: space for parameters and local variables is created internally using a stack. compiler's syntax check for matching braces is implemented by using stack. support for recursion Shebuti Rayana (CS, Stony Brook University) 6

7 Stack: Applications Backtracking. This is a process when you need to access the most recent data element in a series of elements. Think of a labyrinth or maze - how do you find a way from an entrance to an exit? Once you reach a dead end, you must backtrack. But backtrack to where? to the previous choice point. Therefore, at each choice point you store on a stack all possible choices. Then backtracking simply means popping a next choice from the stack. Shebuti Rayana (CS, Stony Brook University) 7

8 Stack Interface The underlying structure for a stack could be, (i) an array, or (ii) a linked list, or (iii) any other collection. Regardless of the type of the underlying data structure, a Stack must implement the same functionality: Allow to add (push) only at the top with running time constant O(1) Allow to remove (pop) only from the top with running time constant O(1) Shebuti Rayana (CS, Stony Brook University) 8

9 Stack API (Cont.) Regardless of whether stack is implemented based on Array or LinkedList, it should have following operations: Shebuti Rayana (CS, Stony Brook University) 9

10 Stack: Linked List Implementation Maintain pointer first/top_of_stack (head) to the first node in a singlylinked list. Push new item before first/top_of_stack. (addtofirst() for Linked List) Pop item from first/top_of_stack. (RemoveFirst() for LinkedList) Shebuti Rayana (CS, Stony Brook University) 10

11 Stack: Linked List Implementation (Cont.) Output: d c b a Shebuti Rayana (CS, Stony Brook University) 11

12 Stack: Push save a link to the list Node oldfirst = first; first oldfirst c b a create a new node for the beginning first = new Node(); null first c b a null oldfirst set the instance variable in the new node first.item = item; First.next = oldfirst; first d c b a null Shebuti Rayana (CS, Stony Brook University) 12

13 Stack: Pop save item to return String item = first delete first node first = first.next; first first c b a c b a null null Return saved item return item Shebuti Rayana (CS, Stony Brook University) 13

14 Stack: Array Implementation (Fixed Capacity) Use array s[] to store N items on stack push(): add new item at s[n] pop(): remove item from s[n-1] Defect: Stack overflows when N exceeds capacity. Shebuti Rayana (CS, Stony Brook University) 14

15 Stack: Array Implementation (Fixed Capacity) Shebuti Rayana (CS, Stony Brook University) 15

16 Stack: Array Implementation (Fixed Capacity) Output: d c b a Shebuti Rayana (CS, Stony Brook University) 16

17 Stack: Array Implementation Considerations Overflow and Underflow Underflow: Occurs when stack is already empty and an attempt to pop() is made Throw exception if pop is called on an empty stack. Overflow: Occurs for fixed capacity implementation by the index of top exceeding the capacity. Use resizing array for array implementation. Shebuti Rayana (CS, Stony Brook University) 17

18 Stack: Array Implementation Considerations Loitering: Holding a reference to an object when it is no longer needed public String pop() { return s[- - top]; } loitering public String pop() { String item = s[- - top]; s[top] = null; return item; } this version avoids "loitering": garbage collector can reclaim memory for an object only if no outstanding references Shebuti Rayana (CS, Stony Brook University) 18

19 Stack: Array Implementation (Resizing Array) Resizing array on push and pop operation push(): increase size of array s[] by 1 pop(): decrease size of array s[] by 1 Shebuti Rayana (CS, Stony Brook University) 19

20 Stack: Array Implementation (Resizing Array) Too expensive. Need to copy all items to a new array, for each operation Array accesses to insert first N items = 1 array access per push N + ( (N 1)) ~ N 2 To expensive for large N 2(n-1) array accesses to expand to size k We must ensure that array resizing happens infrequently Shebuti Rayana (CS, Stony Brook University) 20

21 Stack: Stack: Array Implementation (Resizing Array) Resizing array using repeated doubling strategy: push(): If array is full, create a new array of twice the size, and copy items Shebuti Rayana (CS, Stony Brook University) 21

22 Stack: Array Implementation (Resizing Array) Array accesses to insert first N = 2 i items = 1 array access per push N + ( ^logN) ~ 3N. Much better k array accesses to expand to size k (ignoring cost to create new array) Shebuti Rayana (CS, Stony Brook University) 22

23 Stack: Array Implementation (Resizing Array) Shrinking the array: push(): double size of array s[] when array is full pop(): halve size of array s[] when array is one-half full. Too expensive in worst case. Consider push-pop-push-pop- sequence when array is full. Each operation takes time proportional to N (top). Shebuti Rayana (CS, Stony Brook University) 23

24 Stack: Array Implementation (Resizing Array) Efficient solution push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-quarter full. Array is between 25% and 100% full Shebuti Rayana (CS, Stony Brook University) 24

25 Stack: Array Implementation Performance Amortized analysis: Starting from an empty data structure, average running time per operation over a worst-case sequence of operations. Proposition: Starting from an empty stack, any sequence of M push and pop operations takes time proportional to M. Shebuti Rayana (CS, Stony Brook University) 25

26 Stack: Array Implementation Performance Therefore, n insertions take O(n) time. Shebuti Rayana (CS, Stony Brook University) 26

27 Stack Implementation: Resizing Array vs Linked List Linked-list implementation Every operation takes constant time in the worst case. Uses extra time and space to deal with the links. Resizing-array implementation. Every operation takes constant amortized time. Less wasted space. Shebuti Rayana (CS, Stony Brook University) 27

28 Stack: Complete Implementation Shebuti Rayana (CS, Stony Brook University) 28

29 Stack: Complete Implementation (Linked List) Shebuti Rayana (CS, Stony Brook University) 29

30 Stack: Complete Implementation (Linked List) Shebuti Rayana (CS, Stony Brook University) 30

31 Stack: Complete Implementation (Linked List) Shebuti Rayana (CS, Stony Brook University) 31

32 Stack: Complete Implementation (Array) Shebuti Rayana (CS, Stony Brook University) 32

33 Stack: Complete Implementation (Array) Shebuti Rayana (CS, Stony Brook University) 33

34 Stack: Application 1 Balanced Parenthesis: An arithmetic expression has balanced parenthesis if and only if: the number of left parentheses of each type is equal to the number of right parentheses of each type each right parenthesis of a given type matches to a left parenthesis of the same type to its left and all parentheses in between are balanced correctly. Example: ({A + B} C) Balanced ({A + B) C} Not balanced ({A + B} [C / D]) Balanced (({A + B} C) / D)) Not balanced Shebuti Rayana (CS, Stony Brook University) 34

35 Algorithm: check for balanced parenthesis Scan the expression from left to right. For each left parenthesis that is found, push on the stack For each right parenthesis that is found, If the stack is empty, return false(too many right parentheses) Otherwise, pop the top parenthesis from the stack: If the left and right parentheses are of the same type, discard. Otherwise, return false. If the stack is empty when the scan is complete, return true. Otherwise, return false. (too many left parentheses) Shebuti Rayana (CS, Stony Brook University) 35

36 Trace Shebuti Rayana (CS, Stony Brook University) 36

37 Stack: Application 2 Evaluating Expressions: An expression is fully parenthesized if every operator has a pair of balanced parentheses marking its left and right operands. Not fully-parenthesized: 3 * (5 + 7) 9 (2-4) * (5-7) + 8 Fully-parenthesized: ((3 * (5 + 7)) 9)(((2-4)*(5-7))+ 8) Shebuti Rayana (CS, Stony Brook University) 37

38 General Idea The first operation to perform is surrounded by the innermost set of balanced parentheses. Example:((3 * (5 + 7)) 9) First op: + By reading expression from left to right, first operator comes immediately before first right parenthesis. Replace that subexpression with its result and search for next right parenthesis, etc. Example:((3 * 12) 9) = (36 9) = 27 Shebuti Rayana (CS, Stony Brook University) 38

39 General Idea (cont.) How do we keep track of operands and operators as we read past them in the expression from left to right? Use two stacks: one for operands and one for operators. When we encounter a right parenthesis, pop off one operator and two operands, perform the operation, and push the result back on the operand stack. Shebuti Rayana (CS, Stony Brook University) 39

40 Trace Shebuti Rayana (CS, Stony Brook University) 40

41 Algorithm Let each operand or operator or parenthesis symbol be a token. Let NumStack store the operands. Let OpStack store the operations. For each token in the input expression do If token = operand, NumStack.push(token) If token = operator, OpStack.push(token) If token = ), operand2ß NumStack.pop() operand1ß NumStack.pop() operator ß OpStack.pop() result ß operand1 operator operand2 NumStack.push(result) If token = (, ignore token After expression is parsed, answer ß NumStack.pop() 41

42 Stack: Application 3 Arithmetic Expression: Infix notation: operator is between its two operands (5 + 7) * (7 * 9) Prefix notation: operator precedes its two operands * * 7 9 Postfix notation: operator follows its two operands * * + Shebuti Rayana (CS, Stony Brook University) 42

43 Precedence of Operators Multiplication and division (higher precedence) are performed before addition and subtraction (lower precedence) Operators in balanced parentheses are performed before operators outside of the balanced parentheses. If two operators are of the same precedence, they are evaluated left to right. Shebuti Rayana (CS, Stony Brook University) 43

44 Example Infix expression: A + B * ( C * D E / F ) / G H What is prefix equivalent? + A / * B * C D / E F G H What is postfix equivalent? A B C D * E F / * G / + H Shebuti Rayana (CS, Stony Brook University) 44

45 Evaluating a Postfix Expression Let each operand or operator be a token. Let NumStack store the operands. For each token in the input expression do If token = operand, NumStack.push(token) If token = operator, operand2ß pop() operand1ß pop() result ß operand1 operator operand2 NumStack.push(result) answer ß pop() Shebuti Rayana (CS, Stony Brook University) 45

46 Trace Shebuti Rayana (CS, Stony Brook University) 46

47 Translating Infix to Postfixt Let each operand, operator, or parenthesis be a token. Let OpStack store the operators. Let postfix string P = (empty string) For each token in the input expression do If token = operand, append operand to P If token = operator, push(token) If token = ), append pop() to P If token = (, ignore Shebuti Rayana (CS, Stony Brook University) 47

48 Trace Shebuti Rayana (CS, Stony Brook University) 48

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Structures and List Processing Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Self-referential Structure

More information

Week 4 Stacks & Queues

Week 4 Stacks & Queues CPSC 319 Week 4 Stacks & Queues Xiaoyang Liu xiaoyali@ucalgary.ca Stacks and Queues Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear

More information

Stack Abstract Data Type

Stack Abstract Data Type 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 how Java implements a stack To learn how to implement a

More information

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1 Some Applications of Stack Spring Semester 2007 Programming and Data Structure 1 Arithmetic Expressions Polish Notation Spring Semester 2007 Programming and Data Structure 2 What is Polish Notation? Conventionally,

More information

March 13/2003 Jayakanth Srinivasan,

March 13/2003 Jayakanth Srinivasan, Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION DATA STRUCTURES AND ALGORITHMS 09 STACK APPLICATION REVERSE POLISH NOTATION IMRAN IHSAN ASSISTANT PROFESSOR, AIR UNIVERSITY, ISLAMABAD WWW.IMRANIHSAN.COM LECTURES ADAPTED FROM: DANIEL KANE, NEIL RHODES

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

Formal Languages and Automata Theory, SS Project (due Week 14)

Formal Languages and Automata Theory, SS Project (due Week 14) Formal Languages and Automata Theory, SS 2018. Project (due Week 14) 1 Preliminaries The objective is to implement an algorithm for the evaluation of an arithmetic expression. As input, we have a string

More information

An Introduction to Trees

An Introduction to Trees An Introduction to Trees Alice E. Fischer Spring 2017 Alice E. Fischer An Introduction to Trees... 1/34 Spring 2017 1 / 34 Outline 1 Trees the Abstraction Definitions 2 Expression Trees 3 Binary Search

More information

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017 Stack Applications Lecture 27 Sections 18.7-18.8 Robb T. Koether Hampden-Sydney College Wed, Mar 29, 2017 Robb T. Koether Hampden-Sydney College) Stack Applications Wed, Mar 29, 2017 1 / 27 1 Function

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced Delimiters in an Infix Algebraic Expression A Problem Solved:

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

Stacks Calculator Application. Alexandra Stefan

Stacks Calculator Application. Alexandra Stefan Stacks Calculator Application Alexandra Stefan Last modified 2/6/2018 1 Infix and Postfix Notation The standard notation we use for writing mathematical expressions is called infix notation. The operators

More information

Stacks, Queues (cont d)

Stacks, Queues (cont d) Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Stack Operations on a stack Representing stacks Converting an expression

More information

The Stack and Queue Types

The Stack and Queue Types The Stack and Queue Types Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Programming Principle of the Day Do the simplest thing that could possibly work A good

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

CS W3134: Data Structures in Java

CS W3134: Data Structures in Java CS W3134: Data Structures in Java Lecture #10: Stacks, queues, linked lists 10/7/04 Janak J Parekh HW#2 questions? Administrivia Finish queues Stack/queue example Agenda 1 Circular queue: miscellany Having

More information

Application of Stack (Backtracking)

Application of Stack (Backtracking) Application of Stack (Backtracking) Think of a labyrinth or maze How do you find a way from an entrance to an exit? Once you reach a dead end, you must backtrack. But backtrack to where? to the previous

More information

Lab 7 1 Due Thu., 6 Apr. 2017

Lab 7 1 Due Thu., 6 Apr. 2017 Lab 7 1 Due Thu., 6 Apr. 2017 CMPSC 112 Introduction to Computer Science II (Spring 2017) Prof. John Wenskovitch http://cs.allegheny.edu/~jwenskovitch/teaching/cmpsc112 Lab 7 - Using Stacks to Create a

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

Lecture 4 Stack and Queue

Lecture 4 Stack and Queue Lecture 4 Stack and Queue Bo Tang @ SUSTech, Spring 2018 Our Roadmap Stack Queue Stack vs. Queue 2 Stack A stack is a sequence in which: Items can be added and removed only at one end (the top) You can

More information

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE. Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.3 STACKS AND QUEUES Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu stacks resizing arrays queues generics iterators

More information

Postfix (and prefix) notation

Postfix (and prefix) notation Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator

More information

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal. (Section 2) Linked list implementation of stack Typical Application of stacks Evaluation of expressions (infix, postfix, prefix) References and further details By: Pramod Parajuli, Department of Computer

More information

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions Lecture 4: Applications CS2504/CS4092 Algorithms and Linear Data Structures Dr Kieran T. Herley Department of Computer Science University College Cork Summary. Postfix notation for arithmetic expressions.

More information

Lecture 12 ADTs and Stacks

Lecture 12 ADTs and Stacks Lecture 12 ADTs and Stacks Modularity Divide the program into smaller parts Advantages Keeps the complexity managable Isolates errors (parts can be tested independently) Can replace parts easily Eliminates

More information

Linear Data Structure

Linear Data Structure Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Lecture 3: Stacks & Queues

Lecture 3: Stacks & Queues Lecture 3: Stacks & Queues Prakash Gautam https://prakashgautam.com.np/dipit02/ info@prakashgautam.com.np 22 March, 2018 Objectives Definition: Stacks & Queues Operations of Stack & Queues Implementation

More information

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015 Stack Applications Lecture 25 Sections 18.7-18.8 Robb T. Koether Hampden-Sydney College Mon, Mar 30, 2015 Robb T. Koether Hampden-Sydney College) Stack Applications Mon, Mar 30, 2015 1 / 34 1 The Triangle

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU Data Structures Chapter 06 1 Stacks A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stack. This means that elements are removed from

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed stack method of expression evaluation in 1955. Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 03 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions? Comments? finish RadixSort implementation some applications of stack Priority Queues Michael

More information

CS 171: Introduction to Computer Science II. Linked List. Li Xiong

CS 171: Introduction to Computer Science II. Linked List. Li Xiong CS 171: Introduction to Computer Science II Linked List Li Xiong Roadmap Basic data structure Arrays Abstract data types Stacks Queues Implemented using resizing arrays Linked List Concept and implementations

More information

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016 Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016 The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed

More information

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS AND QUEUES. Problem Solving with Computers-II STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()

More information

Stacks. Revised based on textbook author s notes.

Stacks. Revised based on textbook author s notes. Stacks Revised based on textbook author s notes. Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out

More information

Content: Learning Objectives

Content: Learning Objectives 1 BLOOM PUBLIC CHOOL Vasant Kunj, New Delhi Lesson Plan Class: XII ubject: Computer cience Month : July No of s: 21 Chapter:Data structure: Linked List TTT: 8 WT: 12 Content: Learning Objectives At the

More information

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion. 1. What is the full form of LIFO? The full form of LIFO is Last In First Out. 2. Give some examples for stack application. The examples of stack application are reverse a string, post fix evaluation, infix

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

CSE 230 Intermediate Programming in C and C++ Functions

CSE 230 Intermediate Programming in C and C++ Functions CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions

More information

CSE 413 Final Exam. December 13, 2012

CSE 413 Final Exam. December 13, 2012 CSE 413 Final Exam December 13, 2012 Name The exam is closed book, closed notes, no electronic devices, signal flags, tin-can telephones, or other signaling or communications apparatus. Style and indenting

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Lecture Chapter 6 Recursion as a Problem Solving Technique

Lecture Chapter 6 Recursion as a Problem Solving Technique Lecture Chapter 6 Recursion as a Problem Solving Technique Backtracking 1. Select, i.e., guess, a path of steps that could possibly lead to a solution 2. If the path leads to a dead end then retrace steps

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

CSE 214 Computer Science II Searching

CSE 214 Computer Science II Searching CSE 214 Computer Science II Searching Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction Searching in a

More information

PA3 Design Specification

PA3 Design Specification PA3 Teaching Data Structure 1. System Description The Data Structure Web application is written in JavaScript and HTML5. It has been divided into 9 pages: Singly linked page, Stack page, Postfix expression

More information

Code No: R Set No. 1

Code No: R Set No. 1 Code No: R05010106 Set No. 1 1. (a) Draw a Flowchart for the following The average score for 3 tests has to be greater than 80 for a candidate to qualify for the interview. Representing the conditional

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements

More information

Project 3: RPN Calculator

Project 3: RPN Calculator ECE267 @ UIC, Spring 2012, Wenjing Rao Project 3: RPN Calculator What to do: Ask the user to input a string of expression in RPN form (+ - * / ), use a stack to evaluate the result and display the result

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 Chapter 7 s CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 The Abstract Data Type: Specifications of an abstract data type for a particular problem Can emerge during the design of the

More information

CSE 214 Computer Science II Introduction to Tree

CSE 214 Computer Science II Introduction to Tree CSE 214 Computer Science II Introduction to Tree Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Tree Tree is a non-linear

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms... First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms.... Q1) What are some of the applications for the tree data structure? Q2) There are 8, 15, 13, and

More information

CSE 230 Computer Science II (Data Structure) Introduction

CSE 230 Computer Science II (Data Structure) Introduction CSE 230 Computer Science II (Data Structure) Introduction Fall 2017 Stony Brook University Instructor: Shebuti Rayana Basic Terminologies Data types Data structure Phases of S/W development Specification

More information

Stack and Its Implementation

Stack and Its Implementation Stack and Its Implementation Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1 Definition of Stack Usage of Stack Outline

More information

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5 What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion

More information

A Simple Syntax-Directed Translator

A Simple Syntax-Directed Translator Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called

More information

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted, [1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n

More information

Sample Question Paper

Sample Question Paper Scheme - I Sample Question Paper Marks : 70 Time: 3 Hrs. Q.1) Attempt any FIVE of the following. 10 Marks a. Write any four applications of data structure. b. Sketch the diagram of circular queue. c. State

More information

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this: !! SimpleCalc Objective: To use stacks to emulate a simple arithmetic calculator. Background: Most people learn to write arithmetic expressions like this: which can be entered into a TI calculator, like

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Stacks and their Applications

Stacks and their Applications Stacks and their Applications Lecture 23 Sections 18.1-18.2 Robb T. Koether Hampden-Sydney College Fri, Mar 16, 2018 Robb T. Koether Hampden-Sydney College) Stacks and their Applications Fri, Mar 16, 2018

More information

Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation

Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation Concepts Introduced in Chapter 2 A more detailed overview of the compilation process. Parsing Scanning Semantic Analysis Syntax-Directed Translation Intermediate Code Generation Context-Free Grammar A

More information

Lecture No.04. Data Structures

Lecture No.04. Data Structures Lecture No.04 Data Structures Josephus Problem #include "CList.cpp" void main(int argc, char *argv[]) { CList list; int i, N=10, M=3; for(i=1; i

More information

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework CHAPTER 3 & 4 Stacks & Queues The Collection Framework 1 Stack Abstract Data Type A stack is one of the most commonly used data structures in computer science A stack can be compared to a Pez dispenser

More information

Assessment of Programming Skills of First Year CS Students: Problem Set

Assessment of Programming Skills of First Year CS Students: Problem Set Assessment of Programming Skills of First Year CS Students: Problem Set Notes to the working group participants. Enclosed in this file are the three problems. They are in ascending order of difficulty.

More information

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113)

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113) Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113) 1. The number of interchanges required to sort 5, 1, 6, 2 4 in ascending order using Bubble Sort (A)

More information

CSE 214 Computer Science II Heaps and Priority Queues

CSE 214 Computer Science II Heaps and Priority Queues CSE 214 Computer Science II Heaps and Priority Queues Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction

More information

CS 211 Programming Practicum Fall 2018

CS 211 Programming Practicum Fall 2018 Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Alice E. Fischer Lecture 6: Stacks 2018 Alice E. Fischer Data Structures L5, Stacks... 1/29 Lecture 6: Stacks 2018 1 / 29 Outline 1 Stacks C++ Template Class Functions 2

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Unions and Bit Fields Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Union Like structures, unions are

More information

Examples of attributes: values of evaluated subtrees, type information, source file coordinates,

Examples of attributes: values of evaluated subtrees, type information, source file coordinates, 1 2 3 Attributes can be added to the grammar symbols, and program fragments can be added as semantic actions to the grammar, to form a syntax-directed translation scheme. Some attributes may be set by

More information

TREES. Trees - Introduction

TREES. Trees - Introduction TREES Chapter 6 Trees - Introduction All previous data organizations we've studied are linear each element can have only one predecessor and successor Accessing all elements in a linear sequence is O(n)

More information

UNIT 3

UNIT 3 UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment

More information

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider: Linear, time-ordered structures CS00: Stacks n Prichard Ch 7 n Data structures that reflect a temporal relationship order of removal based on order of insertion n We will consider: first come,first serve

More information

CS 211 Programming Practicum Spring 2017

CS 211 Programming Practicum Spring 2017 Due: Tuesday, 3/28/17 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a JAVA program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

Draw a diagram of an empty circular queue and describe it to the reader.

Draw a diagram of an empty circular queue and describe it to the reader. 1020_1030_testquestions.text Wed Sep 10 10:40:46 2014 1 1983/84 COSC1020/30 Tests >>> The following was given to students. >>> Students can have a good idea of test questions by examining and trying the

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures PD Dr. rer. nat. habil. Ralf Peter Mundani Computation in Engineering / BGU Scientific Computing in Computer Science / INF Summer Term 2018 Part 2: Data Structures PD Dr.

More information

CS Introduction to Data Structures How to Parse Arithmetic Expressions

CS Introduction to Data Structures How to Parse Arithmetic Expressions CS3901 - Introduction to Data Structures How to Parse Arithmetic Expressions Lt Col Joel Young One of the common task required in implementing programming languages, calculators, simulation systems, and

More information

Prefix/Infix/Postfix Notation

Prefix/Infix/Postfix Notation Prefix/Infix/Postfix Notation One commonly writes arithmetic expressions, such as 3 + 4 * (5-2) in infix notation which means that the operator is placed in between the two operands. In this example, the

More information

Foundations of Data Structures

Foundations of Data Structures Foundations of Data Structures Lecture 4 Elementary Abstract Data Types (ADT): Stack Queue 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies:

More information

CSE au Final Exam Sample Solution

CSE au Final Exam Sample Solution CSE 413 12au Final Exam Sample Solution Question 1. (10 points) Regular expressions I. Describe the set of strings generated by each of the following regular expressions. For full credit, give a description

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Infix to Postfix Example 1: Infix to Postfix Example 2: Postfix Evaluation

More information

Stacks II. Adventures in Notation. stacks2 1

Stacks II. Adventures in Notation. stacks2 1 Stacks II Adventures in Notation stacks2 1 The trouble with infix... Rules for expression evaluation seem simple -- evaluate expression left to right, results of each sub-expression becoming operands to

More information

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi Data Structures & Algorithm Analysis Lec(3) Stacks Lecturer: Souad Alonazi What is a stack? Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO It means: the last element

More information

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Bitwise Operators and Enumeration Types Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Overview Bitwise

More information

This is an individual assignment and carries 100% of the final CPS 1000 grade.

This is an individual assignment and carries 100% of the final CPS 1000 grade. CPS 1000 Assignment This is an individual assignment and carries 100% of the final CPS 1000 grade. Important instructions (read carefully and thoroughly): The firm submission deadline is Friday 5 th February

More information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

CISC-235. At this point we fnally turned our atention to a data structure: the stack

CISC-235. At this point we fnally turned our atention to a data structure: the stack CISC-235 20180918 At this point we fnally turned our atention to a data structure: the stack A stack is our frst example of an Abstract Data Type: we specify the operations we need to be able to perform

More information

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers CSE 230 Intermediate Programming in C and C++ Arrays and Pointers Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Definition: Arrays A collection of elements

More information