This document discusses stacks and queues as data structures. It begins by explaining what a stack is, noting that a stack follows last-in, first-out ordering. It then provides an analogy using mail delivery to explain the stack concept. The document goes on to provide Java code examples for implementing a stack. It also gives examples of using a stack to reverse a word and check balanced parentheses. Next, the document defines queues as first-in, first-out data structures and provides Java code for implementing a queue. It concludes by explaining how stacks can be used to parse arithmetic expressions by first converting them to postfix notation.
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
Objectives
Assignment 09: Applications of Stacks
COSC 2336: Data Structures and Algorithms Fall 2020
• More practice with recursion.
• Practice writing some template functions.
• Use stack ADT to implement given algorithms.
• Practice using Stack class container given as a library in a separate file. • Look at some common applications of stacks.
Description
In this assignment, you will be using the Stack abstract data type we developed for this unit and discussed in our lectures, to implement 4 functions that use a stack data type to accomplish their algorithms. The functions range from relatively simple, straight forward use of a stack, to a bit more complex. But in all 4 cases, you should only need to use the abstract stack interface functions push(), pop(), top(), and isEmpty() in order to successfully use our Stack type for this assignment and the function you are asked to write.
NOTE
You are to use the Stack ADT abstraction give to you for this assignment. If you are familiar with STL stack containers, you are not to use them for this assignment. Part of the assignment is to look over and learn the Stack ADT implementation we give you here based on our textbook Stack examples.
Setup
For this assignment you will be given the following files:
File Name
assg09-tests.cpp assg09-stackfun.hpp assg09-stackfun.cpp Stack.hpp
Stack.cpp
Description
Unit tests for the member functions
you are to write.
Header file where function prototypes for the functions you write using stacks should go. Implementaiton file, the implementation of the 4 functions you write for this assignment go here. Header file defining a Stack ADT for use in implementing the functions for this assignment. You will not make any modifications in this file, you are only going to be using the given Stack. Implementation file for the Stack ADT
template class. You also do not make any changes in this file either.
Set up a multi-file project to compile the .cpp source files and run them as shown for the class. The Makefile you were given should be usable to create a build project using the Atom editor as required in this class. You will only be adding code to the assg09-stackfun.[hpp|cpp] file in this assignment. The Stack.[hpp|cpp] file contains a Stack container. You are to use this Stack ADT for the 4 functions you are to write for this assignment.
1
The general approach you should take for this assignment, and all assignment is:
Set up your project with the given starting code. The files should compile and run, but either no tests will be run, or tests will run but be failing.
For this project, start by uncommenting the first TEST_CASE in the assg09-tests.cpp file. These are the unit tests to test the functionality of your doParenthesisMatch() function, the member function you are to implement.
AddthecorrectfunctionprototypeforthedoParenthesisMatch()memberfunctionintheassg09-stackfun.hpp header file. The prototyp.
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
Abstract Data Types
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
(b) Write out a signature, or interface, that defines the operations of a stack ADT.
(c) Consider a string of characters of the form
... (.( ... ).) ...
where ... indicates an arbitrary sequence of characters (except for parentheses),
(.( indicates an arbitrary number (one or more) of opening parentheses, and
similarly ).) indicates an arbitrary number of closing parentheses.
Using only the stack abstraction operations defined above, write pseudocode for
an algorithm that determines, using a stack, whether or not the number of closing
parentheses is the same as the number of opening parentheses.
You may assume the existence of a function read(str,ch) that reads the next character
of string str into ch.
You may also assume that you can invoke a function reportFail, that will cause
termination with failure, and similarly, reportSuccess causes termination with a
success indication.
Further, you may also assume that you can call a function newStack(S) to create
a new empty stack S, and eos(str) that returns false when you reach the end of
the string.
Solution
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
A data type is a collection of values and a set of operations on those values. That collection and
these operations form a mathematical construct that may be implemented with the use of a
particular hardware or software data structure. The term abstract data type (ADT) refers to the
basic mathematical concept that defines the data type. We have discussed four different
implementations of the list data structure.
In case of implementation of the list with the use of an array, the size of the array gives difficulty
if increased.
To avoid this, we allocate memory dynamically for nodes before connecting these nodes with the
help of pointers.
For this purpose, we made a singly linked list and connected it with the next pointer to make a
chain.
Moving forward is easy but going back is a difficult task.
To overcome this problem, we made a doubly linked list using prev andnext pointers. With the
help of these pointers, we can move forward and backward very easily. Now we face another
problem that the prev pointer of first node and the next pointer of the last node are NULL.
Therefore, we have to be careful in case of NULL pointers. To remove the NULL pointers, we
made the circular link list by connecting the first and last node.
The program employing the list data structure is not concerned with its implementation.
We do not care how the list is being implemented whether through an array, singly linked list,
doubly linked list or circular linked list. It has been witnessed that in these four implementations
of the list, the interface remained the same i.e. it implements the same methods like add, get,
next, start a.
Using a circularly-linked list made the solution trivial. The solution would have been more difficult if an array had been used. This illustrates the fact that the choice of the appropriate data structures can significantly simplify an algorithm. It can make the algorithm much faster and efficient.
queue datastructure made easy and datastructure explained in java. visit http://technoexplore.blogspot.com and http://hotjobstuff.blogspot.com for some other important presentations.
Contents
COSC 2436 – LAB4
TITLE .............................................................................................................................................................. 1 TIME TO COMPLETE ...................................................................................................................................... 1 COURSE OBJECTIVES – LEARNING OUTCOME .............................................................................................. 1 LAB OBJECTIVES ............................................................................................................................................ 2 SKILLS REQUIRED........................................................................................................................................... 2 HOW TO DO EACH PART ............................................................................................................................... 2 REQUIREMENT .............................................................................................................................................. 3
LAB4 PART1 ............................................................................................................................................... 3
LAB4 PART2 ............................................................................................................................................... 4 HOW TO TURN IN THE LAB ........................................................................................................................... 6 HOW TO GRADE THE LAB.............................................................................................................................. 6
Note: in the instruction of the lab change “yourLastName” to your last name. In the example, change Smith to your last name, change James Smith to your full name, change Mary Lane to the name that users type in from the keyboard (if these words are in this instruction)
TITLE
Restricted Data Structure: Stack and Queue -Evaluating the infixed Math expression
TIME TO COMPLETE
Two week
COURSE OBJECTIVES
–
LEARNING OUTCOME
[LO1]
Provide UML class diagram and the code of data type classes
Provide the pseudo-code or flowchart based on the requirement of a project before writing the code of the driver class. Also, can access data members of data type classes
Describe and implement the inheritance relationship between super class and child classes.
Can use abstract classes or interface and apply polymorphism to the real life problem project
[LO3]
Describe and implement operations of Stack and Queue structures. Using Stack/Queue to the real life problem project
LAB OBJECTIVES
-Complete the lab on time (Time Management) -Can write the pseudo-code
-Can provide UML of data type class
-Can write comments in the program
-Can write the code of data type classes including data members, no-argument constructor, parameter constructors, mutator methods, ass.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Lesson 4 stacks and queues
1. Lesson 4 – Stacks and
Queues
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM BY: AREGATON
2. What is stacks?
A stack allows access to only one data item: the last item inserted. If you remove this item, you
can access the next-to-last item inserted, and so on. This capability is useful in many
programming situations. In this section we’ll see how a stack can be used to check whether
parentheses, braces, and brackets are balanced in a computer program source file. At the end of
this chapter, we’ll see a stack playing a vital role in parsing (analyzing) arithmetic expressions
such as 3*(4+5).
Most microprocessors use a stack-based architecture. When a method is called, its return
address and arguments are pushed onto a stack, and when it returns, they’re popped off. The
stack operations are built into the microprocessor.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 2
3. The Postal Analogy
To understand the idea of a stack, consider an analogy provided by the U.S.
Postal Service. Many people, when they get their mail, toss it onto a stack
on the hall table or into an “in” basket at work. Then, when they have a
spare moment, they process the accumulated mail from the top down. First,
they open the letter on the top of the stack and take appropriate action—
paying the bill, throwing it away, or whatever.
After the first letter has been disposed of, they examine the next letter
down, which is now the top of the stack, and deal with that. Eventually, they
work their way down to the letter on the bottom of the stack (which is now
the top). Figure 4.1 shows a stack of mail.
This “do the top one first” approach works all right as long as you can easily
process all the mail in a reasonable time. If you can’t, there’s the danger
that letters on the bottom of the stack won’t be examined for months, and
the bills they contain will become overdue.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 3
4. Java Code for a Stack
Let’s examine a program, stack.java, that implements a stack using a class called StackX. Listing
4.1 contains this class and a short main() routine to exercise it.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 4
5. Java Code for a Stack
Continued:
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 5
6. Output:
The main() method in the StackApp class creates a stack that can hold 10 items, pushes 4 items
onto the stack, and then displays all the items by popping them off the stack until it’s empty.
Here’s the output:
80 60 40 20
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 6
7. Stack Example 1: Reversing a Word
For our first example of using a stack, we’ll examine a very simple task: reversing a word. When
you run the program, it asks you to type in a word. When you press Enter, it displays the word
with the letters in reverse order.
A stack is used to reverse the letters. First, the characters are extracted one by one from the
input string and pushed onto the stack. Then they’re popped off the stack and displayed.
Because of its Last-In-First-Out characteristic, the stack reverses the order of the characters.
Listing 4.2 shows the code for the reverse.java program.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 7
8. Stack Example 1: Reversing a Word
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 8
9. Stack Example 1: Reversing a Word
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 9
10. We’ve created a class Reverser to handle the reversing of the input string. Its key component is
the method doRev(), which carries out the reversal, using a stack. The stack is created within
doRev(), which sizes the stack according to the length of the input string.
In main() we get a string from the user, create a Reverser object with this string as an argument
to the constructor, call this object’s doRev() method, and display the return value, which is the
reversed string.
Here’s some sample interaction with the program:
Enter a string: part
Reversed: trap
Enter a string:
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 10
11. What is Queues?
The word queue is British for line (the kind you wait in). In Britain, to “queue up “means to get in
line. In
Computer science a queue is a data structure that is somewhat like a stack, except that in a
queue the first item inserted is the first to be removed (First-In-First-Out, FIFO), while in a stack,
as we’ve seen, the last item inserted is the first to be removed (LIFO). A queue works like the
line at the movies:
The first person to join the rear of the line is the first person to reach the front of the line and
buy a ticket. The last person to line up is the last person to buy a ticket (or—if the show is sold
out—to fail to buy a ticket). Figure 4.4 shows how such a queue looks.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 11
12. Basic Queues
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 12
The two basic queue operations are
inserting an item, which is placed at the
rear of the queue, and removing an item,
which is taken from the front of the
queue. This is similar to a person joining
the rear of a line of movie-goers and,
having arrived at the front of the line and
purchased a ticket, removing herself from
the front of the line.
13. Basic Queues
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 13
The terms for insertion and removal in a
stack are fairly standard; everyone says
push and pop. Standardization hasn’t
progressed this far with queues. Insert is
also called put or add or enque, while
remove may be called delete or get or
deque. The rear of the queue, where
items are inserted, is also called the back
or tail or end. The front, where items are
removed, may also be called the head.
We’ll use the terms insert, remove, front,
and rear.
14. Java Code for a Queue
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 14
15. Java Code for a Queue
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 15
We’ve chosen an approach in which Queue class fields include
not only front and rear, but also the number of items currently
in the queue: nItems. Some queue implementations don’t use
this field; we’ll show this alternative later.
16. The insert() Method
The insert() method assumes that the queue is not full. We don’t show it in
main(), but normally you should call insert() only after calling isFull() and getting
a return value of false. (It’s usually preferable to place the check for fullness in
the insert() routine and cause an exception to be thrown if an attempt was
made to insert into a full queue.)
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 16
17. The remove() Method
The remove() method assumes that the queue is not empty. You should call
isEmpty() to ensure this is true before calling remove(), or build this error-
checking into remove().
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 17
18. The peek() Method
The peek() method is straightforward: It returns the value at front.
Some implementations allow peeking at the rear of the array as well;
such routines are called something like peekFront() and peekRear()
or just front() and rear().
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 18
19. The isEmpty(), isFull(), and size() Methods
The isEmpty(), isFull(), and size() methods all rely on the
nItems field, respectively checking if it’s 0, if it’s maxSize, or
returning its value.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 19
20. Parsing Arithmetic Expressions
So far in this chapter, we’ve introduced three different data storage
structures. Let’s shift gears now and focus on an important
application for one of these structures. This application is parsing
(that is, analyzing) arithmetic expressions such as 2+3 or 2*(3+4) or
((2+4)*7)+3*(9–5). The storage structure it uses is the stack. In the
brackets.java program (Listing 4.3), we saw how a stack could be
used to check whether delimiters were formatted correctly. Stacks
are used in a similar, although more complicated, way for parsing
arithmetic expressions.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 20
21. Parsing Arithmetic Expressions
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 21
As it turns out, it’s fairly difficult, at least for a computer algorithm, to evaluate an arithmetic
expression directly. It’s easier for the algorithm to use a two-step process:
1. Transform the arithmetic expression into a different format, called postfix notation.
2. Evaluate the postfix expression.
Before we delve into the details of steps 1 and 2, we’ll introduce postfix notation.
22. Postfix Notation
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 22
Everyday arithmetic expressions are written with an operator (+, –, *, or /) placed between two
operands (numbers, or symbols that stand for numbers). This is called infix notation because the
operator is written inside the operands. Thus, we say 2+2 and 4⁄7, or, using letters to stand for
numbers, A+B and A⁄B.
23. How Humans Evaluate Infix
How do you translate infix to postfix? Let’s examine a slightly easier
question first: How does a human evaluate a normal infix
expression? Although, as we stated earlier, such evaluation is difficult
for a computer, we humans do it fairly easily because of countless
hours in Mr. Klemmer’s math class. It’s not hard for us to find the
answer to 3+4+5, or 3*(4+5). By analyzing how we evaluate this
expression, we can achieve some insight into the translation of such
expressions into postfix.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 23
24. Roughly speaking, when you “solve” an
arithmetic expression, you follow rules
something like this:
1. You read from left to right. (At least, we’ll assume this is true. Sometimes people skip ahead,
but for purposes of this discussion, you should assume you must read methodically, starting at
the left.)
2. When you’ve read enough to evaluate two operands and an operator, you do the calculation
and substitute the answer for these two operands and operator. (You may also need to solve
other pending operations on the left, as we’ll see later.)
3. You continue this process—going from left to right and evaluating when possible—until the
end of the expression.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 24
25. Roughly speaking, when you “solve” an
arithmetic expression, you follow rules
something like this:
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 25
26. Roughly speaking, when you “solve” an
arithmetic expression, you follow rules
something like this:
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 26
29. Java Code to Convert Infix to Postfix
Listing 4.7 shows the infix.java program, which uses the rules from Table 4.10 to translate an
infix expression to a postfix expression.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 29
30. Java Code to Convert Infix to Postfix
Listing 4.7 shows the infix.java program, which uses the rules from Table 4.10 to translate an
infix expression to a postfix expression.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 30
31. Java Code to Convert Infix to Postfix
Listing 4.7 shows the infix.java program, which uses the rules from Table 4.10 to translate an
infix expression to a postfix expression.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 31
32. SUMMARY
• Stacks, queues, and priority queues are data structures usually used to simplify certain programming operations.
• In these data structures, only one data item can be accessed.
• A stack allows access to the last item inserted.
• The important stack operations are pushing (inserting) an item onto the top of the stack and popping (removing) the item that’s on the top.
• A queue allows access to the first item that was inserted.
• The important queue operations are inserting an item at the rear of the queue and removing the item from the front of the queue.
• A queue can be implemented as a circular queue, which is based on an array in which the indices wrap around from the end of the array to the beginning.
• A priority queue allows access to the smallest (or sometimes the largest) item.
• The important priority queue operations are inserting an item in sorted order and removing the item with the smallest key.
• These data structures can be implemented with arrays or with other mechanisms such as linked lists.
• Ordinary arithmetic expressions are written in infix notation, so-called because the operator is written between the two operands.
• In postfix notation, the operator follows the two operands.
• Arithmetic expressions are typically evaluated by translating them to postfix notation and then evaluating the postfix expression.
• A stack is a useful tool both for translating an infix to a postfix expression and for evaluating a postfix expression.
4/4/2021 PC-108 DATA STRUCTURE AND ALGORITHM 32