Suggested Solution

Task 1 Task 2 Task 3 Task 4 Task 5
Task 1 Task 2 Task 3 Task 4 Task 5

Task 1

We can perform the following operations on a stack:

  • push(item), this will add an item to the stack
  • pop(), this will remove the item at the top of the stack (last-in)
  • isEmpty(), this will check if the stack is empty or not. We can use it before attempting to pop()!

A stack, s, exists. Draw the resulting stack after the following operations have been executed. Indicate the top of the stack in your answer:

s.push("s")

s.push("t")

s.pop()

s.push("a")

s.pop()

s.pop()

s.push("c")

s.push("k")

Task 2

A function takes a stack as a parameter. It pops the contents of the stack into an empty String. Finally it displays the string.

Using pseudocode, implement the displayString function. Its signature is:

function displayString(Stack s)

make sure you use the isEmpty() operation (hint: use a while loop and keep popping while the stack is not empty!)

Task 3

A function, checkPalindrome, takes a String as a parameter.

Using an empty stack and stack operations, it attempts to determine if the stack is a palindrome.

Implement the checkPalindrome function. Its signature is:

function checkPalindrome(String word)

Task 4

A class of Jacks, Jills and Joes exist. The name of each student is stored in a stack, s.

The name at the top of the image is at position 0 in the stack.

The name at the bottom of the image was added to the stack first.

A function countName(name) takes as string as a parameter.

The function processes the stack and returns a count of how many items in the stack are the same as the string parameter.

Write pseudocode to implement this function. Its signature is:

function countName(String name)

Task 5

A stack, s, of positive whole numbers exists.

The number at the top of the image is at position 0 in the stack.

The number at the bottom of the image was added to the stack first.

A function getMaxIndex() determines and outputs the index of the maximum number in the stack.

Write pseudocode to implement this function. Its signature is:

function getMaxIndex()

What change would you make to your algorithm if the stack included negative numbers too?