You are on page 1of 7

Data Structures & Algorithms Sheet #6 - Solution

Cairo University
Faculty of Engineering
Computer Engineering Department
Data Structures and Algorithms
Sheet #6 - Solution
Stacks and Queues Commented [E1]:
This sheet consists of:
Part 1 Exercises  Tracing Problems
Part 2 Problems  Algorithm Problems
Part I: Exercises A. Stack Problems
B. Queue Problems

The concept of Abstract Data Type (ADT) should be


illustrated here.

We make an ADT that provide the user with set of operations


to use it directly without knowing the complication of their
implementation.

For example:
1-Stack
Operations: push, pop, and stack top (pop without removing
element from stack).
2- Queue
Operations: enqueue, dequeue, queue front (returns front
element without removing), queue rear (returns rear element
without removing)

Now, in any algorithm we’ll deal with stacks and queues as


black boxes by just calling the operations or functions they
provide.

Stacks and Queues inside can be implemented by:


1- linked list implementation
OR
2- array implementation
Each make the operations in O (1).

This implementation thing will be discussed in the lab. Here,


we’re dealing with them more as ADT (black boxes).

Note:
1-Most of the problems needs drawing the stack and queue
to make them imagine what they have and if they need temp
stacks or queues.
2-In tracing problems, write statement number besides its
effect in the drawn stack or queue; Dr. asked them to do that
in exams.
3-You can refer to the project that they have to choose the DS
and implement it then use it as black box with functions they
provide.
Commented [E2]:
S (from top down): 5, 12, 2, 3
Q (from front to rear): 8, 12
x = 12
y=5
Commented [E3]:
Q1 (from front): -
Q2 (from front): 20, 12
S (from top): 6, 2

CMP N102 1/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

Commented [E4]:
Q (from front): 5, 7, 12, 4, 4, 4, 6, 8, 67, 34, 23, 5, 5, 44, 33,
22, 6, 6
x=6

Important to make them note that the default reading data is


from left to right because they usually ask about that in
exams.

Commented [E5]:
Q1 (from front): -
Q2 (from front): 5, 5, 7, 7, 12, 12, 4, 4, 0, 0, 4, 4, 6, 6

CMP N102 2/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

Commented [E6]:
Q (from front): 7, 5, 34, 67, 8, 6, 4, 33, 44
S (from top): -

Commented [E7]:
Q1 (from front): 20, 25, 14, 10, 11, 12, 15
Q2 (from front): -
Q3 (from front): -

CMP N102 3/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

Part II: Problems

A. Stack Problems

7. Write an algorithm to implement two stacks using only one array. Your stack algorithm should Commented [M. Ismail8]: Problem [7]
not declare an overflow unless every slot in the array is used. The tops of the stacks should grow in reverse order
i.e. Top1 grows from 0 up
and Top2 grows from N-1 down
8. A palindrome is a string that can read backward and forward with the same result. Stack is full if Top2=Top1+1
E.g., the following is a palindrome: MADAM
Further, a more general palindrome is one that ignores spacing, punctuation, and
capitalization, such as the following is also a palindrome: Go dog and Madam, I’m
Adam
Write an algorithm that checks if a given string is a general palindrome.

Input: string str of length n


Output: true if str is palindrome, false otherwise
Preconditions: -
Postconditions: -
Algorithm isPalindrome(str, n)
Stack s;
// use stack to store the reversed string
for i from 0 to n-1
c = lower (str[i]);
if (c not space nor punctuation)
push(s, c);
end if
end for
//pop from the stack and check with the original string (not reversed)
for i from 0 to n-1
c = lower (str[i]);
if (c not space nor punctuation)
x = pop(s);
if(x != c) return false; //return after finding the 1st mismatch
end if
end for
return true; //must wait till the end of the for loop to return true

9. Write algorithm print_reverse that prints a linked list in reverse order. (Do not use recursion). Commented [M. Ismail9]: Problem [9]
Loop on the linked list
For each node, store node data into a stack
10. Write the pseudocode for an algorithm called copyStack that copies the contents of one stack When end of list is reached, Print data stored in the stack
into another. The algorithm passes two stacks, the source stack and the destination stack. The ========================
Another solution is to store nodes addresses into the stack
order of the stacks must be identical. rather than the data itself.
This is a better solution if data stored in each node is large.
Commented [M. Ismail10]:
Problem[10]

A third temporary stack is needed to preserve the order

CMP N102 4/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

11. Write algorithm catStack that takes 2 stacks s1 and s2 and concatenates the contents of s2 on
top stack s1. Note: s2 is unchanged. For example, if s1 = {1, 2, 3 top} and s2 = {4, 5 top} then
s1 should be: {1, 2, 3, 4, 5 top} and s2 is unchanged.
Input: stack s1 and stack s2
return: -
Preconditions: -
Postconditions: concatenates s2 on top of s1, so s1 = s1 + s2, s2 is unchanged
Algorithm catStack(s1, s2)
Stack temp;
//pop from s2 and push in temp
while (s2 not empty)
x = pop(s2)
push(temp, x)
end while
//pop from temp and push in s1 and s2
while (temp not empty)
x = pop(temp)
push(s1, x)
push(s2, x) //to make s2 unchanged
end while

12. Write an algorithm reverseStack that reverses the contents of a stack (the top and bottom
elements exchange positions, the second and the element just before the bottom exchange
positions, and so forth until the entire stack is reversed).
a. Solve with the help of auxiliary stack(s) only. Commented [M. Ismail11]:
b. Solve with the help of auxiliary queue(s). Problem [12.a]
Two auxiliary stacks are needed

13. One of the applications of a stack is to backtrack—that is, to retrace its steps. Commented [M. Ismail12]:
Problem [12.b]
As an example, imagine we read a list of items, such that: Only one auxiliary queue is needed
• Each time we read a negative number we must backtrack and print the five numbers that Commented [E13]:
come before the negative number (starting from the one previous to the negative Use a stack to solve this problem.
1
number) and then discard the negative number. Read the numbers and push them into the stack (without
• If there are fewer than five items in the stack, print an error message and return. printing them) until a negative number is read.
• The program stops normally without an error message when zero is entered. 2
At this time, stop reading and pop five items from the stack
Write the pseudocode that solves this problem and test it with the following data: and print them.
1 2 3 4 5 -1 1 2 3 4 5 6 7 8 9 10 -2 11 12 -3 1 2 3 4 5 If there are fewer than five items in the stack, print an error
message and stop the program.
3
Algorithm backtrack() After printing the five items, resume reading data and placing
Stack s; them in the stack.
4
read x; When 0 is entered, the program stops normally.
while (x != 0)
if (x > 0) //non-negative
push(s, x);
else //negative
for i = 1 to 5
if (s is empty)
print ‘Error’;
return;
end if
x = pop(s)
print x;
end for
end if
read x;
end while

CMP N102 5/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

B. Queue Problems

14. Using only the algorithms in the queue ADT (i.e. only queue operations), write an algorithm
called catQueue that concatenates two queues together. The second queue should be put at
the end of the first queue.

15. Write an algorithm called queueToStack that creates a stack from a queue. At the end of the
algorithm, the queue should be unchanged; the front of the queue should be the top of the
stack, and the rear of the queue should be the base of the stack

Input: queue q
Return: stack s
Preconditions: -
Postconditions: -
Algorithm queueToStack(q)
Stack s;
Stack tempSt
Queue tempQ
//dequeue from q and push in temp
while (q not empty)
x = dequeue(q);
push(tempSt, x);
enqueue(tempQ, x);
end while
//pop from tempST and push in s
while (tempSt not empty)
x = pop(tempSt);
push(s, x);
end while
//dequeue from tempQ and enqueue in q
while (tempQ not empty)
x = dequeue(tempQ)
enqueue(q, x);
end while
return s;

CMP N102 6/7 Spring 2018


Data Structures & Algorithms Sheet #6 - Solution

16. Write an algorithm called compressString that compresses a string by deleting all space Commented [E14]:
characters in the string. (Hint: One way to do so is to use a queue of characters) 1
Insert non-space characters from the string into the queue.
2
Input: string str When you reach the end of the string, dequeue the characters
Output: - from the queue and place them back into the string.
Preconditions: -
Postconditions: all spaces in str is removed
Algorithm compressString(str)
Queue q; //queue of characters
//read str characters and enqueue if not space
while (not end of str)
x = str[i];
if(x not space)
enqueue(q, x);
end if
end while
//dequeue from q and print
i=0
while (q not empty)
x = dequeue(q);
str[i] = x;
increment i
end while
str [i] = ‘\0’ //insert null character at the end of the string

17. Given a queue of integers, write an algorithm queueSumAndAvg that, using only the queue Commented [M. Ismail15]:
ADT, calculates and prints the sum and the average of the integers in the queue without Problem [17]
Need to deque each item and accumulate sum and increment
changing the contents of the queue. a counter
Then you should enqueue the item again
The problem is how to detect the end of queue items??
18. Given a queue of integers, write an algorithm deleteNegatives that deletes all negative integers So an auxiliary queue is needed
without changing the order of the remaining elements in the queue.
Commented [M. Ismail16]:
Problem [18]
19. Write an algorithm reverseQueue that reverses the contents of a queue. Similar to 17
An aux. queue is needed

Input: queue q
Output: -
Preconditions: -
Postconditions: q is reversed
Algorithm reverseQueue(q) //reverse then stack
Stack s;
//dequeue from q and push in s
while (q not empty)
x = dequeue(q);
push(s, x);
end while
//pop from s and enqueue in q
while (s not empty)
x = pop(s);
enqueue(q);
end while

20. Using only the algorithms in the queue ADT, write an algorithm isIdentical that checks the
contents of two queues and returns true if they are identical and false if they are not.

CMP N102 7/7 Spring 2018

You might also like