Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Course: DSA

Homework 02
Stack - Queue
Given the StackQueue source code folder, students conduct the following tasks.
Students can use LinkedList<>, Stack<>, and Queue<> in Java API for this homework.

Task 1:
Add to StackEx class the following method to evaluate postfix arithmetic expressions
public int evaluate(String exp)
● Args:
○ exp: a space-separated arithmetic expression in postfix format, i.e.,
23+4*89+-
● Return:
○ an integer
Note: students should refer to the given algorithm in the lecture presentation.

Copy and paste source code of the method here


public static int evaluate(String exp)
{
Stack<Integer> stack = new Stack<>();
String[] substr = exp.split(" ");
for (String s : substr)
{
if (isNumeric(s))
{
stack.push(Integer.parseInt(s));
}
else
{
int operand1 = stack.pop();
int operand2 = stack.pop();
int result = calculate(operand1, operand2, s);
stack.push(result);
}
}
if (!stack.isEmpty()) {
return stack.pop();
} else {
// Handle invalid expression
throw new IllegalArgumentException("Invalid postfix
expression");
}
}
public static boolean isNumeric(String s)
{
try
{
Integer.parseInt(s);
return true;
}
catch (Exception e)
{
return false;
}
}

public static int calculate(int operand1, int operand2, String


operator)
{
switch (operator)
{
case "+":
return operand2 + operand1;
case "-":
return operand2 - operand1;
case "*":
return operand2 * operand1;
case "/":
return operand2 / operand1;
default:
throw new IllegalArgumentException();
}
}

Task 2:
Add to QueueEx class the following method to extract lower-case letters of a string and then
concatenate them in the same order.
public String extractLow(String s)
● Args:
○ s: a string whose letters are alphabetic
● Return:
○ a string
For example:
● input: “AcBddeF”
● output: “cdde”

Copy and paste source code of the method here


public static String extractLow(String s)
{
Queue<Character> queue = new LinkedList<>();
char[] char_arr = s.toCharArray();
for (char c : char_arr)
{
if (Character.isLowerCase(c))
{
queue.add(c);
}
}
String result = "";
while (!queue.isEmpty())
{
result += queue.poll();
}
return result;
}

Submission Notice:
● Export your answer file as pdf
● Rename the pdf following the format:
hw02_<student number>_<Full Name>.pdf
E.g: hw02_123456_NguyenThanhAn.pdf
If you have not been assigned a student number yet, then use 123456 instead.
● Careless mistakes in filename, format, question order, etc. are not accepted (0 pts).

You might also like