Advanced Java Concepts Unit 3: Stacks and Queues

Size: px
Start display at page:

Download "Advanced Java Concepts Unit 3: Stacks and Queues"

Transcription

1 Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO). Think of a stack of plates; the last plate placed on the stack is the first one you take off. Java does have a Stack Class; here are some of its methods. Method Boolean empty() E peek() E pop() void push( E element) int size() Description Precondition: the stack is not empty Returns the object at the top of the stack (but does not remove it) Precondition: the stack is not empty Removes and returns the object at the top of the stack Adds an element to the top of the stack Note. Java implements the Stack class as a subclass of the Vector class which implements the List interface. You will need an import statement whenever you need to use this class. 1. Why do people criticize Java s stack class? What alternative could have been used? 2. What does this code snippet display? 3. This code compiles. Will there be a run-time error? If yes, explain. If no error, what is displayed? Stack<Integer> st = new Stack<Integer>(); st.push( 1 ); st.push( 2 ); st.push( 3 ); import java.util.*; public class TryStacks { public static void main(string[] args) { Stack<String> st = new Stack<String>(); st.push( "A" ); st.push( "B" ); System.out.println( st.peek() ); Page 1

2 One area where stacks are used is in memory management. The exact details of how computer memory is managed depend on the computer s operating system and the programming language. However, the following simplified description can be useful. Whenever a method is called, an activation record is created. This activation record includes any parameters, local variables, and probably other things I m not aware of. This activation record is placed on the stack an area of program memory reserved for this purpose. When the method is complete, the activation record is popped off the stack. The top most activation record on the stack is the method currently being executed. 4. A program has a main method and two other methods: method A and method B. The figure to the right shows the current state of the program s stack. Which statement is TRUE? a) methoda is currently running. b) methodb is currently running. c) The main method is currently running. d) There is not enough information to answer this. 5. Given the current state of the program s stack, what do you know about methoda? Note. While nothing may be technically correct for you, it is not the correct answer for this question. methodb methoda main methoda methoda main top of stack top of stack Program. Here is an algorithm for converting a non-negative base 10 number to a base 2 number. 1. Find the remainder when the number is divided by two. Push the remainder onto a stack. 2. Number = number / 2 3. Go back to step 1. Keep repeating as long as the number is greater than zero. 4. Print out the contents of the stack (i.e. print the topmost first, then the second and so on). Write a program that implements the above algorithm. After you get the basic version working, clean it up as follows: Instruct the user to enter an integer between 0 and Convert the number into base 2. Add leading zeroes (if needed) so that there is a total of 16 zeroes and ones. When you print the result, add a blank space between every four bits. For example, If the user enters 513, your program should display If the user enters 60013, your program should display If the user enters 0, your program should display Your prompt to the user must be: System.out.println( "Integer?" ); Page 2

3 Evaluating Arithmetic Expressions. Before we discuss how stacks are used in evaluating arithmetic expressions, we need to discuss the three ways an expression can be written. Form Description Example infix Each operator is located between its operands This is the form you know and love. prefix The operator is placed to the left of the operands. This is also known as Polish notation. postfix The operator is placed to the right of the operands. This is also known as Reverse Polish notation Infix notation sometimes requires the use of parentheses. Prefix and postfix notation do not require (and therefore do not use) parentheses. In fact, in prefix and postfix notation the order of operations is completely determined by the order of the operators. Some early (1970 s and 80 s) handheld calculators required that users enter the expressions in reverse Polish notation. Please read the Wikipedia articles, (prefix) and (postfix) on these topics. To evaluate an expression in prefix notation, you scan the statement from left to right. As soon as you see two adjacent operands, you perform the operation specified by the operator immediately preceding it. Then you replace the operator and two operands with the result. Keep repeating until you have a result. IMPORTANT. If the result of a particular operation is a negative number, then the resulting operand is negative (you are not adding a subtraction operator to the expression). Here are a couple of examples. + * scanning left to right we find the operands 3 and 4 and the operator right before them is * so we multiply them together and replace them with so we add 12 and 5 together 17 is the result Another example / scanning left to right the first pair of operands we find is 8 and 2 so we divide them and replace / 8 2 with replace with replace with is an operand, add -6 and 3 together -3 is the result Problems 8 to 12. Evaluate the following prefix expressions. 8) / ) / + * ) * ) + 10 / * ) * Page 3

4 To evaluate an expression in postfix notation, you scan the statement from left to right. As soon as you see two adjacent operands followed by an operator, you perform the operation specified and replace the operator and two operands with the result. Keep repeating until you have a result For example: * scanning left to right we find the operands 6 and 7 and the operator right after them is + so we add them together and replace them with * multiple 13 by 2 26 is the result Another example * - 2 / scanning left to right the first pair of operands followed by an operator we find so we replace that with * - 2 / replace 6 9 * with / replace with / -51 is an operand, divide -51 by is the result Problems 13 to 17. Evaluate the following postfix expressions. 13) * 14) * 15) / + * 16) 9 2 * 3 5 * + 17) / * * I ll leave it up to you to find out how to convert prefix and postfix expression into the corresponding infix expressions and vice versa. Problems 18 to 22. Rewrite each statement from infix form to prefix and postfix forms. YOU MUST KEEP THE OPERANDS IN THE SAME ORDER (sorry for shouting). Infix Prefix Postfix * * * (2 + 3)(4 5) (5 2) Page 4

5 Program. Complete the Eval class. Given a valid postfix expression, the evalpostfix method will return the value of that expression. The method should be able to handle multiplication, division, addition, and subtraction. You may assume that there is exactly one space between each operator/operand. public class Eval{ public static int evalpostfix( String s ){ Call the split method to create a String array that consists of the numbers and operands in the string. All spaces should be removed. Create an Integer stack. Iterate through the array. If the element is a number, push it onto a stack. If the element is an operator, pop the last two elements off the stack, evaluate the expression and push the result onto the stack. When you are finished iterating through the array, the size of the stack should be one. Pop that value off the stack and return it. Suggestion: Write a helper method that determines if a string is a number. This can be done by using the Character.isDigit method though remember that the number could be positive or negative. Or you could write a method that checks by using a try-catch thingee. Does this sound familiar? Maybe? (Voice getting higher each time.) Queues are linear collections in which elements can only be added to one end and you can only remove elements from the other end. Think of a line to buy tickets. When people arrive they go to the end of the line; the person at the head of the line is the next person to be served. This is called a first-in, first-out protocol (FIFO). Java has a Queue interface to support this abstract data type. Some Methods of the Queue Interface Method Description boolean add( E element ) Adds element to the rear of the queue and returns true if room is available or returns false otherwise. boolean isempty() Returns true if the queue is empty. E peek() Returns the object at the front of the queue or null if the queue is empty. E remove() Precondition: the queue is not empty. Removes and returns the object at the front of the queue. int size() Returns the number of objects in the queue. The LinkedList class implements the Queue interface. Page 5

6 By the way. The Queue interface defines some methods that do similar things, but one set of methods throws exceptions when things go bad, the other methods return special values. Type of Operation Throws Exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek() There are different queues and some use one set over the other. Here s very short program that uses a Queue. import java.util.*; public class Example { public static void main(string[] args) { Queue<String> q = new LinkedList<String>(); q.add( "A" ); q.add( "B" ); // prints A // prints B Program. Given a queue of strings, write a method that will print the contents of the queue without changing the order of the elements. Write a second method that remove elements of the queue that match another string, with changing the order of the remaining elements. This is program 3.03 on repl.it Program. Ok. Bear with me on this one. The idea is to model cars stopping at a traffic light. There is a Car class and in the main method cars are added, modified, and removed from a queue in response to various inputs/events. Everything is speeded up. For example, in one test run, I had the traffic light on for 4 seconds and off for 4 seconds and a new car show up every 2 seconds. After 60 seconds there were 10 cars backed up at the light. Car Class Instance Variables and Constructor final int RESPONSE_TIME How many seconds before the driver responds to the light going green. int timetogo How many seconds until the driver is awake and will drive. When the light goes green, these values are decremented every second the light is green. When the light goes red, these are reset to RESPONSE_TIME int spot This is where they are in line. 1 is in front. int speed This determines how many spots they may advance when the light goes green (given those spots are not occupied). Car( int distance) distance initializes spot. RESPONSE_TIME is random [1,3] timetogo is initialized to RESPONSE_TIME speed is random [1,3] Page 6

7 Car Class Methods Comments void moveforward( int x ) x is the next available spot. If the driver is awake, they will move as far as their speed lets them, but not past x void roll() The car moves forward one spot. The driver does not have be awake. The idea is this method is only called when (1) the spot in front of this car is empty and (2) the light is red. int getspot() return spot; void timepasses() Decrements timetogo by one. This is called when the light is green. timetogo may be negative. boolean readytogo() return timetogo <= 0; void resettimetogo() timetogo = RESPONSE_TIME; String tostring() return timetogo + "_" + spot; Please do not change the Car class. Here is a quick outline of the main method. The user says how long the light is on and off. Also, how often new cars are added to the queue. The simulation last 60 seconds. Not 60 actual seconds, 60 iterations where each iteration represents a second. The light is green at the start. In each iteration o add a car to the queue if it s time o change the light to change from red to green or green to red when appropriate. When it turns red, call the resettimetogo for every car in the queue o if it s green call the timepasses method for each car in the queue call the moveforward method for each car in the queue remove the car at the head of the queue if its spot is less than 1 o if it s red, call the roll method for each car in the queue when the spot in front is open (do that by checking what spot the car in front of it is in). o print out the time, whether the light is on or off, and call the tostring method for each car in the queue and print that o pause the program for 300 milliseconds. To the right is one possible result. The first column is the time. true means the light is on. Each number pair is a car. The first number is how more time until the driver wakes up. The second number is the car s spot in line. In the loop, a car is added and then may act and then data is printed. For instance, at end of time 0, 2_1 means that car will need 2 more seconds to wake up and they are at spot 1. At the end of time 2, the first has left the second driver is also very slow to respond and is still in spot 2. Page 7

8 Priority Queues are like queues in that items are added to the end of the queue and removed from the head of the queue. They are different in that more important elements go to the head of the line. For example, imagine an emergency room at a hospital. As people arrive they get in line and wait their turn. However, if someone comes in with a life-threatening problem, they go to the head of the line. Java has a PriorityQueue class that implements the Queue interface. The default constructor places objects in the queue according to their natural order which is defined by how they implement the Comparable interface (i.e. the compareto method). The item with the smallest value is removed first. For example, in the String class A is less than B so it will go to the head of the queue. import java.util.*; public class Example { public static void main(string[] args) { PriorityQueue<String> q = new PriorityQueue<String>(); q.add( "B" ); q.add( "A" ); q.add( "H" ); q.add( "C" ); // prints A // prints B // prints C // prints H Note. Suppose you have a class named Dog that does not implement Comparable. The following code will compile: PriorityQueue<Dog> q = new PriorityQueue<Dog>(); Dog d1 = new Dog( "hank" ); Dog d2 = new Dog( "bob" ); q.add( d1 ); q.add( d2 ); However, when you try to run it you will get the following runtime error: java.lang.classcastexception: Dog cannot be cast to java.lang.comparable Page 8

9 Queues and Priority Queues 24. What is displayed? Queue<Integer> q = new LinkedList<Integer>(); q.add( 14 ); q.add( 5 ); q.add( 12 ); 25. What is displayed? PriorityQueue<Integer> q = new PriorityQueue<Integer>(); q.add( 14 ); q.add( 5 ); q.add( 12 ); 26. What is displayed? Queue<String> q = new LinkedList<String>(); q.add( "M" ); q.add( "G" ); q.add( "K" ); while (! q.isempty() ) 27. What is displayed? PriorityQueue<String> q = new PriorityQueue<String>(); q.add( "M" ); q.add( "G" ); q.add( "K" ); while (! q.isempty() ) 28. What is displayed? PriorityQueue<String> q = new PriorityQueue<String>(); q.add( "apple" ); q.add( "a" ); q.add( "xray" ); q.add( "Adam" ); q.add( "ZOO!" ); while (! q.isempty() ) The ASCII code for A is 65. The ASCII code for a is 97. Program. This program models an emergency room and it has three classes. The Patient class obviously represents patients in a hospital. Each patient has a condition ranked from 1 (worst) to 10 (not too bad). The ERqueue class represents the ER room treating patients in order of worst to best condition. The main method creates an ERqueue objects and adds an array of Patients to the ERqueue object. Methods are called. Results are printed. Go to repl.it for more details. Page 9

CSE 2123: Collections: Priority Queues. Jeremy Morris

CSE 2123: Collections: Priority Queues. Jeremy Morris CSE 2123: Collections: Priority Queues Jeremy Morris 1 Collections Priority Queue Recall: A queue is a specific type of collection Keeps elements in a particular order We ve seen two examples FIFO queues

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

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

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

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

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

Building Java Programs

Building Java Programs Building Java Programs Appendix Q Lecture Q-1: stacks and queues reading: appendix Q 2 Runtime Efficiency (13.2) efficiency: measure of computing resources used by code. can be relative to speed (time),

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

Queues. Stacks and Queues

Queues. Stacks and Queues Queues Reading: RS Chapter 14 Slides are modified from those provided by Marty Stepp www.buildingjavaprograms.com 1 Stacks and Queues Sometimes a less powerful, but highly optimized collection is useful.

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 143. Lecture 4: Stacks and Queues

CSE 143. Lecture 4: Stacks and Queues CSE 143 Lecture 4: Stacks and Queues Stacks and queues Sometimes it is good to have a collection that is less powerful, but is optimized to perform certain operations very quickly. Today we will examine

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 07 / 26 / 2016 Instructor: Michael Eckmann Today s Topics Comments/Questions? Stacks and Queues Applications of both Priority Queues Michael Eckmann - Skidmore

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

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II Adam Blank Lecture 5 Winter 2015 CSE 143 Computer Programming II CSE 143: Computer Programming II Stacks & Queues Questions From Last Time 1 Can we include implementation details in the inside comments

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

Stacks and Queues. Chapter Stacks

Stacks and Queues. Chapter Stacks Chapter 18 Stacks and Queues 18.1 Stacks The stack abstract data type allows access to only one element the one most recently added. This location is referred to as the top of the stack. Consider how a

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

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

Assignment 5. Introduction

Assignment 5. Introduction Assignment 5 Introduction The objectives of this assignment are to exercise a few advanced object oriented programming and basic data structures concepts. The first mini-goal is to understand that objects

More information

Complexity, General. Standard approach: count the number of primitive operations executed.

Complexity, General. Standard approach: count the number of primitive operations executed. Complexity, General Allmänt Find a function T(n), which behaves as the time it takes to execute the program for input of size n. Standard approach: count the number of primitive operations executed. Standard

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

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ). Assignment 5 Introduction For this assignment, you will write classes to evaluate arithmetic expressions represented as text. For example, the string "1 2 ( * 4)" would evaluate to 15. This process will

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

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

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

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

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

CSC 321: Data Structures. Fall 2012

CSC 321: Data Structures. Fall 2012 CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

CSC 222: Computer Programming II. Spring 2005

CSC 222: Computer Programming II. Spring 2005 CSC 222: Computer Programming II Spring 2005 Stacks and recursion stack ADT push, pop, peek, empty, size ArrayList-based implementation, java.util.stack application: parenthesis/delimiter matching postfix

More information

CS 211 Programming Practicum Spring 2018

CS 211 Programming Practicum Spring 2018 Due: Thursday, 4/5/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

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract Data Types Stack January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract data types and data structures An Abstract Data Type (ADT) is: A collection of data Describes what data are stored but

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

Problem with Scanning an Infix Expression

Problem with Scanning an Infix Expression Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix

More information

// The next 4 functions return true on success, false on failure

// The next 4 functions return true on success, false on failure Stacks and Queues Queues and stacks are two special list types of particular importance. They can be implemented using any list implementation, but arrays are a more practical solution for these structures

More information

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example Stacks and Queues Introduction to abstract data types (ADTs) Stack ADT applications interface for Java Stack ex use: reverse a sequence of values Queue ADT applications interface for Java Queue Time permitting:

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

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

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

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

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

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. 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

-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

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator CMPSCI 187 / Spring 2015 Postfix Expression Evaluator Due on Thursday, 05 March, 8:30 a.m. Marc Liberatore and John Ridgway Morrill I N375 Section 01 @ 10:00 Section 02 @ 08:30 1 CMPSCI 187 / Spring 2015

More information

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 54 Assignment on Data Structures (Refer Slide

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

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

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/2016 23:59 People in-charge: R. Mairon and Y. Twitto Introduction The objectives of this assignment are to exercise a few advanced object

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

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack.

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack. Stacks and Queues 4.3 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 3- Stacks Some familiar stacks What is a stack? Add item on top of stack Remove item that is topmost Last In, First Out LIFO Specifications of the ADT Stack Specifications

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

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template

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

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

CSCI 200 Lab 4 Evaluating infix arithmetic expressions CSCI 200 Lab 4 Evaluating infix arithmetic expressions Please work with your current pair partner on this lab. There will be new pairs for the next lab. Preliminaries In this lab you will use stacks and

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack. STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is

More information

CS 307 Final Spring 2009

CS 307 Final Spring 2009 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2009 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

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 373 Data Structures and Algorithms. Lecture 2: Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues CSE 373 Data Structures and Algorithms Lecture 2: Queues Queue ADT queue: A list with the restriction that insertions are done at one end and deletions are done at the other First-In, First-Out ("FIFO

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

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

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

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

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API Stacks and Queues 4.3 Stacks and Queues Fundamental data types. Set of operations (add, remove, test if empty) on generic data. Intent is clear when we insert. Which item do we remove? Stack. Remove the

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

CSC 321: Data Structures. Fall 2013

CSC 321: Data Structures. Fall 2013 CSC 321: Data Structures Fall 2013 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats

Chapter 5. A Closer Look at Instruction Set Architectures. Chapter 5 Objectives. 5.1 Introduction. 5.2 Instruction Formats Chapter 5 Objectives Understand the factors involved in instruction set architecture design. Chapter 5 A Closer Look at Instruction Set Architectures Gain familiarity with memory addressing modes. Understand

More information

Data Structure. Recitation IV

Data Structure. Recitation IV Data Structure Recitation IV Topic Java Generics Java error handling Stack Lab 2 Java Generics The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello");

More information

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified. The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The

More information

Plan for Week. What is a linear structure? Stacks Queues and Deques, Oh My!

Plan for Week. What is a linear structure? Stacks Queues and Deques, Oh My! Plan for Week What is a linear structure? Linear structures: Stack, Queue Ø Applications: LIFO, FIFO, other Ø Canonical examples and view to more Ø Java specifics of how to use these Friday: More examples

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

Chapter 5. A Closer Look at Instruction Set Architectures

Chapter 5. A Closer Look at Instruction Set Architectures Chapter 5 A Closer Look at Instruction Set Architectures Chapter 5 Objectives Understand the factors involved in instruction set architecture design. Gain familiarity with memory addressing modes. Understand

More information

Project 1: Implementation of the Stack ADT and Its Application

Project 1: Implementation of the Stack ADT and Its Application Project 1: Implementation of the Stack ADT and Its Application Dr. Hasmik Gharibyan Deadlines: submit your files via handin by midnight (end of the day) on Thursday, 10/08/15. Late submission: submit your

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

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print) Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 SOLUTIONS Your name (Please print) 1. Suppose you are given a singly-linked

More information

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Collections: Collection terminology The Java Collections API Abstract nature of collections

More information

Plan for Week. Linear structures: Stack, Queue. Friday: More examples of recursion and alternatives. Guide to using practice-it for APT-like problems

Plan for Week. Linear structures: Stack, Queue. Friday: More examples of recursion and alternatives. Guide to using practice-it for APT-like problems Plan for Week Linear structures: Stack, Queue Ø Applications: LIFO, FIFO, other Ø Canonical examples and view to more Ø Java specifics of how to use these Friday: More examples of recursion and alternatives

More information

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs 1 Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs Michael Albert michael.albert@cs.otago.ac.nz Keywords: abstract data type, collection, generic class type, stack 2 Collections

More information

4.3 Stacks and Queues

4.3 Stacks and Queues 4.3 Stacks and Queues Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 03/30/12 04:33:08 PM Data Types and Data Structures Data types.

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics HW Tips QT Creator dos & don ts ADTs Stack Example: Reverse-Polish Notation calculator Queue Event queues QT Creator A F E W W A R N I N

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

15-122: Principles of Imperative Computation, Fall 2015

15-122: Principles of Imperative Computation, Fall 2015 15-122 Programming 5 Page 1 of 10 15-122: Principles of Imperative Computation, Fall 2015 Homework 5 Programming: Clac Due: Thursday, October 15, 2015 by 22:00 In this assignment, you will implement a

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

CSE 143 SAMPLE MIDTERM SOLUTION

CSE 143 SAMPLE MIDTERM SOLUTION CSE 143 SAMPLE MIDTERM SOLUTION 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust

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

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT CSCI 204 Introduction to Computer Science II 1. Objectives In this lab, you will practice the following: Learn about the Stack ADT Implement the Stack ADT using an array Lab 6: Stack ADT Use a Stack to

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

COMP 250 Winter stacks Feb. 2, 2016

COMP 250 Winter stacks Feb. 2, 2016 Stack ADT You are familiar with stacks in your everyday life. You can have a stack of books on a table. You can have a stack of plates on a shelf. In computer science, a stack is an abstract data type

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

3137 Data Structures and Algorithms in C++

3137 Data Structures and Algorithms in C++ 3137 Data Structures and Algorithms in C++ Lecture 3 July 12 2006 Shlomo Hershkop 1 Announcements Homework 2 out tonight Please make sure you complete hw1 asap if you have issues, please contact me will

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

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

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

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

Stacks, Queues and Hierarchical Collections

Stacks, Queues and Hierarchical Collections Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by

More information