Stacks
Stacks
Q1: Please show how the following postfix expression can be evaluated using Stack as shown in
the class. Please show the stack contents and the operations.
4 7 5 3 + * 16 9 - / *
Ans: 32
a. S.push(52);
b. S.push(52);
c. S.push(S.peek()*2);
d. System.out.println(S.size()); 104 36
e. System.out.println(S.pop()); 52 28
f. S.pop(); 52 0
g. System.out.println(S.size());
i. Q.enqueue(28);
j. Q.enqueue(Q.first()%3);
k. System.out.println(Q.first())
l. System.out.println(Q.dequeue());
m. System.out.println(S.pop());
104
36
36
Q3: What are the benefits of implementing stack using a LinkedList rather than an array based
implementation?
LinkedList<string> ArrayList<Integer>
push()
pop() add ()
peek() remove()
isEmpty() set()
size() get()
toString() size()
Queue:
n. Q.enqueue(24)
o. Q.enqueue(74)
p. Q.enqueue(34)
q. Q.first()
r. Q.dequeue()
s. Q.enqueue(12)
t. Q.dequeue()
Please show the queue contents at the end of these operations. Clearly show the front and rear of
the queue.
24 74 34 12
34 12
Algorithm Analysis:
Q5: Please identify the time complexity of following code (using Big O notation). Assume that
eval(val);
Ans: O(n2)
Q6. What is the time complexity (in Big O) of the method test_code? Assume that test_1 has
complexity O(logn), test_2 has complexity O(n) and test_3 has complexity O(n 3). Briefly explain
why?
Ans: O(n3)
Q7. A program creates a queue. The program takes array of user names as String and then performs
following operations:
- If the user name starts with A to S, it will add (enqueue) to the queue
- If the user name starts with T to Z, it will remove (dequeue) one element from the queue and
then add both the user names to the queue.
What will the queue look like if the input array is as follows? Please clearly label front and rear of the
queue.
Q8. Please run the ticket counter simulation code with following parameters:
How many cashiers are needed to keep the average customer wait time below 10 minutes?
Ans:
Customer customer;
{
for (int count = 0; count < cashiers; count++)
cashierTime[count] = 0;
totalTime = 0;
while (!(customerQueue.isEmpty()))
if (!(customerQueue.isEmpty()))
customer = customerQueue.remove();
start = customer.getArrivalTime();
else
start = cashierTime[count];
customer.setDepartureTime(departs);
cashierTime[count] = departs;
totalTime += customer.totalTime();
}
}