2.3 Stacks Question Paper

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

Name: ________________________

2.3 Stacks
Class: ________________________

Date: ________________________

Time: 202 minutes

Marks: 141 marks

Comments:

Page 1 of 24
Q1.
To evaluate an expression in Reverse Polish notation, you start from the left hand side of
the expression and look at each item until you find an operator (eg + or −).

This operator is then applied to the two values immediately preceding it in the expression.
The result obtained from this process replaces the operator and the two values used to
calculate it. This process continues until there is only one value in the expression, which is
the final result of the evaluation.

For example 5 2 7 + + would change to 5 9 + after the first replacement.

Explain how a stack could be used in the process of evaluating an expression in Reverse
Polish notation.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 3 marks)

Q2.
Two frequently completed actions when using a particular piece of software are undo and
repeat.

The undo action results in the state changing from the current state to the state previous
to the user’s most recent action, eg if the last action the user completed was to change
the font of a selected piece of text from Courier New to Chiller then if the undo action is
selected the result will be to change the font of that text back to Courier New .

The user is able to keep using the undo action to go back through all previous states.

The repeat action results in the user’s most recent action being applied again, eg if the
last action the user completed was to change the font of a piece of text to Chiller then if
the repeat action is selected the result will be to change the font of the currently selected
text to Chiller.

The user is able to keep using the repeat action to apply the most recent action multiple
times. The repeat action will only work when there is a most recent action that can be
applied again.

(a) Explain how a single stack can be used in the implementation of the repeat action
and the undo action.

___________________________________________________________________

___________________________________________________________________

Page 2 of 24
___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(5)

(b) State the type of error that occurs if the user tries to complete an undo action before
they have completed any other actions.

___________________________________________________________________

___________________________________________________________________
(1)
(Total 6 marks)

Q3.
A graph can be drawn to represent a maze. In such a graph, each graph vertex
represents one of the following:

• the entrance to or exit from the maze

• a place where more than one path can be taken

• a dead end.

Edges connect the vertices according to the paths in the maze.

Diagram 1 shows a maze and Diagram 2 shows one possible representation of this
maze.
Position 1 in Diagram 1 corresponds to vertex 1 in Diagram 2 and is the entrance to the
maze. Position 7 in Diagram 1 is the exit to the maze and corresponds to vertex 7.
Dead ends have been represented by the symbol in Diagram 2.

Diagram 3 shows a simplified undirected graph of this maze with dead ends omitted.

Page 3 of 24
Diagram 2 Diagram 3

Representation of maze Graph representing maze


including dead ends with dead ends omitted

(a) The graph in Diagram 3 is a tree.

State one property of the graph in Diagram 3 that makes it a tree.

___________________________________________________________________

___________________________________________________________________
(1)

(b) The graphs of some mazes are not trees.

Describe a feature of a maze that would result in its graph not being a tree.

___________________________________________________________________

___________________________________________________________________
(1)

(c) Complete the table below to show how the graph in Diagram 3 would be stored
using an adjacency matrix.

Page 4 of 24
(2)

(d) (i) What is a recursive routine?

______________________________________________________________

______________________________________________________________
(1)

(ii) To enable the use of recursion a programming language must provide a stack.

Explain what this stack will be used for and why a stack is appropriate.

______________________________________________________________

______________________________________________________________

______________________________________________________________

______________________________________________________________
(2)

Diagram 3 is repeated here so that you can answer Question (e) without having to turn
pages.

Page 5 of 24
(e) A recursive routine can be used to perform a depth-first search of the graph that
represents the maze to test if there is a route from the entrance (vertex 1) to the exit
(vertex 7).

The recursive routine in the diagram below is to be used to explore the graph in
Diagram 3. It has two parameters, V (the current vertex) and EndV (the exit vertex).

Procedure DFS(V, EndV)


Discovered[V] ← True

If V = EndV Then Found True←


For each vertex U which is connected to V Do
If Discovered [U] = False Then DFS(U, EndV)
EndFor
CompletelyExplored[V] ← True
EndProcedure

Complete the trace table below to show how the Discovered and
CompletelyExplored flag arrays and the variable Found are updated by the
algorithm when it is called using DFS(1,7).

The details of each call and the values of the variables V, U and EndV have already
been entered into the table for you. The letter F has been used as an abbreviation
for False. You should use T as an abbreviation for True.

Page 6 of 24
(5)
(Total 12 marks)

Q4.
Reverse Polish Notation is an alternative to standard infix notation for writing arithmetic
expressions.

(a) Convert the following Reverse Polish Notation expressions to their equivalent infix
expressions.

Reverse Polish Notation Equivalent Infix Expression

45 6 +

12 19 + 8 *
(2)

(b) State one advantage of Reverse Polish Notation over infix notation.

___________________________________________________________________

___________________________________________________________________
(1)

Page 7 of 24
(c) The pseudo-code algorithm below can be used to calculate the result of evaluating
a Reverse Polish Notation expression that is stored in a string. The algorithm is
designed to work only with the single digit denary numbers 0 to 9. It uses
procedures and functions listed in the table below, two of which operate on a stack
data structure.

StringPos ← 0
Repeat
StringPos ← StringPos + 1
Token ← GetCharFromString(InputString, StringPos)
If Token = ‘+’ Or Token = ‘-’ Or Token = ‘/’ Or Token = ‘*’
Then
Op2 ←Pop()
Op1 ← Pop()
Case Token Of
‘+’: Result ← Op1 + Op2
‘-’: Result ← Op1 - Op2
‘/’: Result ← Op1 / Op2
‘*’: Result ←Op1 * Op2
EndCase
Push(Result)
Else
IntegerVal ←ConvertToInteger(Token)
Push(IntegerVal)
EndIf
Until StringPos = Length(InputString)
Output Result

Procedure/Function Purpose Example(s)


GetCharFromString
Returns the character GetCharFromString
(InputString:String
at position StringPos ("Computing", 1)
,
StringPos:Integer): within the string would return the
Char InputString. character 'C'.
GetCharFromString
Note that the leftmost
("Computing", 3)
letter is position 1, not
would return the
position 0.
character 'm'.
ConvertToInteger Returns the integer ConvertToInteger('4'
(ACharacter: Char): equivalent of the
Integer ) would return the
character in integer value 4.
ACharacter.

Length (AString: Returns a count of the Length("AQA") would


String): Integer number of characters in return the integer value
the string AString. 3.

Push (ANumber: Puts the number in Push(6) would put the


Integer) ANumber onto the stack. number 6 on top of the
stack.

Pop (): Integer Removes the number


from the top of the stack
X ← Pop() would
and returns it. remove the value from
the top of the stack and
put it in X.

(d) Complete the table below to trace the execution of the algorithm when

Page 8 of 24
InputString is the string: 64+32+*

In the Stack column, show the contents of the stack once for each iteration of the
Repeat..Until loop, as it would be at the end of the iteration.

The first row and the leftmost column of the table have been completed for you.

StringPos Token IntegerVal Op1 Op2 Result Stack

0 - - - - -

Page 9 of 24
(5)

Final output of algorithm: ______________________________________________


(1)

(e) A programmer is going to implement the algorithm above in a programming


language that does not provide built-in support for a stack data structure.

The programmer intends to simulate a stack by using a fixed length array of 20


integers named StackArray with indices running from 1 to 20 and an integer
variable TopOfStackPointer which will be initialised to 0.

Write a pseudo-code algorithm for the Push operation to push a value stored in the
variable ANumber onto the stack.

Your algorithm should cope appropriately with any potential errors that might occur.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(4)
(Total 13 marks)

Q5.
(a) State the principle of operation of a set of data values which behave as a stack.

___________________________________________________________________

___________________________________________________________________
(1)

(b) Memory locations 600 to 605 are to be used as a stack area to store character data,
and the first value added to the stack is to be stored at address 600.

Figure 1 shows the initial empty state of the stack.

Figure 1
600

Page 10 of 24
601

602

603

604

605

(i) Show on Figure 2 the state of the stack after the characters ‘A’, ‘V’, ‘E’, ‘R’
and ‘Y’ join the stack.

Figure 2
600

601

602

603

604

605

(1)

(ii) Two items are removed from the stack. Show on Figure 3 the state of the
stack.

Figure 3
600

601

602

603

604

605

(1)

(iii) Two new characters ‘S’ and ‘P’ join the stack. Show on Figure 4 the final
state of the stack.

Figure 4
600

601

Page 11 of 24
602

603

604

605

(1)

(c) The original items in this stack are to be reversed. This can be done using a second
data structure which uses locations 700 to 705 respectively. The first item added to
the stack was character ‘A’.

Figure 5

600 ‘A’ 700 600

601 ‘V’ 701 601

602 ‘E’ 702 602

603 ‘R’ 703 603

604 ‘Y’ 704 604

605 705 605

Stack Stack
(before the operation) (i) ____________ (after the operation)

(i) Name the second data structure. Label Figure 5.

______________________________________________________________
(1)

(ii) Describe Step 1 in Figure 5.

______________________________________________________________

______________________________________________________________
(1)

(iii) Describe Step 2 in Figure 5.

______________________________________________________________

______________________________________________________________
(1)

(iv) Show on Figure 5 the final contents of all the memory locations.
(2)

Page 12 of 24
(Total 9 marks)

Q6.
A recursively-defined procedure ProcA that takes two integers as parameters is defined
below.

(a) What is meant by a recursively-defined procedure?

___________________________________________________________________

___________________________________________________________________
(1)

(b) What is the role of the stack when a recursively-defined procedure is executed?

___________________________________________________________________

___________________________________________________________________
(1)

(c) Dry run the procedure call ProcA(11,1) using the data in the array, Items, by
completing the trace table below.

Items
Procedure ProcA (Number,Entry) [1] 4
If Number <> Items[Entry] [2] 5
Then ProcA (Number,Entry+1) [3] 8
Else Output (Entry) [4] 11
EndIf [5] 15
EndProc
[6] 19
[7] 21
[8] 28
[9] 33

Number Entry Output

11 1

(4)

(d) What is the purpose of this algorithm?

___________________________________________________________________
(1)

Page 13 of 24
(e) Give a situation where this algorithm will fail.

___________________________________________________________________

___________________________________________________________________
(1)

(f) Suggest a modification to the algorithm that will prevent it from failing.

___________________________________________________________________

___________________________________________________________________
(1)

(g) With an ordered array, Items, of many more entries, what more efficient algorithm
could be used to achieve your expressed purpose in part (d)?

___________________________________________________________________

___________________________________________________________________
(1)
(Total 10 marks)

Q7.
A stack may be implemented by using either an array or a linked list.

(a) Give a disadvantage of:

(i) an array implementation;

______________________________________________________________
(1)

(ii) a linked list implementation.

______________________________________________________________
(1)

(b) Under what circumstances would it be more appropriate to use:

(i) an array;

______________________________________________________________
(1)

(ii) a linked list.

______________________________________________________________
(1)
(Total 4 marks)

Q8.
(a) In the context of data structures what is meant by the terms:

Page 14 of 24
(i) FIFO; _________________________________________________________

(ii) LIFO? ________________________________________________________


(2)

(b) Queue and stack are examples of data structures. Tick in the following table to
indicate whether they are FIFO or LIFO data structures.

FIFO LIFO

Queue

Stack
(2)

(c) Describe one example of the use of a stack.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

(d) Describe one example of the use of a Binary Search Tree.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)
(Total 8 marks)

Q9.
A recursively-defined procedure Process, which takes an integer as its single parameter,
is defined below.

(a) What is meant by recursively-defined?

___________________________________________________________________

___________________________________________________________________
(1)

(b) Describe how a stack is used in the execution of procedure Process?

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

Page 15 of 24
(c) Dry run the procedure call Process(1), using the data in the table below, showing
clearly the order the values are printed.

Procedure Process (P)


Print (P)
If Table[P].Left <> 0
Then Process (Table[P].Left)
EndIf
Print (Table[P].Data)
If Table[P].Right <> 0
Then Process (Table[P].Right)
EndIf
EndProcedure

Table

Data Left Right

[1] Jones 3 2

[2] Smith 0 0

[3] Bremner 5 4

[4] Fortune 0 0

[5] Bird 0 0

Printed Output:=
______________________________________________________

___________________________________________________________________
(6)

(d) What does procedure Process describe?

___________________________________________________________________
(1)
(Total 10 marks)

Q10.
A stack is a type of abstract data type (ADT) that is often known as a LIFO data type. A
stack with a single element 27 may be drawn as follows:

(a) What is the meaning of the term LIFO?

___________________________________________________________________

Page 16 of 24
(1)

(b) A stack has two operations, Push and Pop. Push n adds item n to stack. Pop
removes one item from the stack. A number of operations are performed, in
sequence, on the stack drawn above. Using the stack diagrams below show the
effect of this sequence of operations.

(i) Push 5

(1)

(ii) Push 9

(1)

(iii) Pop

(1)

(iv) Push 6

(1)

(c) Give one example of the use of a stack.

___________________________________________________________________
(1)
(Total 6 marks)

Page 17 of 24
Q11.
A recursively-defined procedure B, which takes an integer as its single parameter, is
defined below. The operators DIV and MOD perform integer arithmetic.
x DIV y calculates how many times y divides exactly into x. For example 7 DIV 3 = 2
x MOD y calculates the remainder that results. For example 7 MOD 3 = 1.

Procedure B (Number)
If (Number = 0) OR (Number = 1)
Then Print (Number)
Else
B (Number DIV 2)
Print (Number MOD 2)
EndIf
EndProcedure

(a) What is meant by recursively-defined?

___________________________________________________________________

___________________________________________________________________
(1)

(b) Why is a stack necessary to execute procedure B recursively?

___________________________________________________________________

___________________________________________________________________
(1)

(c) Dry run the procedure call B(53) showing clearly the values of the parameter and
the printed output for the six calls of B.

Call Number Parameter

1 53

2 26

3 13

Printed Output: ______________________________________________________


(6)

(d) What process does procedure B describe? ________________________________


(1)
(Total 9 marks)

Q12.
Describe how the elements in a non-empty queue are reversed with the aid of a stack.

Page 18 of 24
_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________
(Total 4 marks)

Q13.
The following data is input to a program, in alphabetical order, and is stored.

Anne
Bob
Claire
Dean

(a) Draw a diagram to show how this data is stored for:

(i) a stack;

(ii) a queue.

(4)

(b) One item is retrieved from these data structures for processing, and Eden is input.

Draw the diagrams of this new situation for:

(i) the stack;

Page 19 of 24
(ii) the queue.

(3)

(c) Why are queues in computer systems usually implemented as circular queues?

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)
(Total 9 marks)

Q14.
The list Ports contains the following names:

[Southampton, Barcelona, Athens, Alexandria, Tunis, Lisbon]

The table below shows some functions which take a list as their single argument and
return a result which is either an element of a list or a boolean value.

Head(list) – If the list is non-empty, it returns the element at the head of the list
(e.g. Head (Ports)  Southampton) otherwise it reports an error

Tail(list) – If the list is non-empty it returns a new list containing all but the first
element of the original list, otherwise it reports an error

Empty(list) – if the list is the empty list it returns True otherwise it returns False.
The empty list is donated by [ ]

(a) What result is returned when the following function calls are made?

(i) Tail(Ports) _____________________________________________________

______________________________________________________________
(1)

(ii) Head(Tail(Tail(Ports))) ____________________________________________

______________________________________________________________
(2)

(iii) Empty(Tail(Tail(Tail(Tail(Tail(Tail(Ports))))))) __________________________

______________________________________________________________

Page 20 of 24
(2)

A recursively defined procedure P, which takes a list as its single parameter, is defined
below.
Define Procedure P(list)
If Not Empty(list)
Then
P(Tail(list))
Print Head(list)
EndIf
EndDefine

(b) What is meant by recursively defined?

___________________________________________________________________

___________________________________________________________________
(1)

(c) Explain why a stack is needed to execute procedure P recursively.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(2)

(d) For the procedure call P(Ports) give the PRINTed output in the order in which it is
produced.

___________________________________________________________________

___________________________________________________________________
(4)

(e) Complete the table to show the list Ports as a linked list so that the ports can be
accessed in alphabetical order.

(2)
(Total 14 marks)

Page 21 of 24
Q15.
Explain how the elements in a non-empty queue may be reversed with the aid of a stack.

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

_________________________________________________________________ ______

_______________________________________________________________________

_______________________________________________________________________
(Total 4 marks)

Q16.
An algebraic expression is represented in a binary tree as follows:

(a) Label its root, a branch and a leaf node.


(3)

(b) Mark and label the left sub-tree and the right sub-tree of this tree.
(2)

A recursively-defined procedure T, which takes a tree structure, tree(x, y, z) as its single


parameter, where x is the root, y is the left sub-tree and z is the right sub-tree, is defined
below (<> means not equal to).

Procedure T (tree(x, y, z))

If y <> empty
Then
PRINT ‘)’
T(y)
EndIf
PRINT x
If z <> empty
Then
T(z)
PRINT ‘)’

Page 22 of 24
EndIf
EndProc

(c) What is meant by recursively-defined?

___________________________________________________________________

___________________________________________________________________
(1)

(d) Explain why a stack is necessary in order to execute procedure T recursively.

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________
(3)

(e) Dry run the following procedure call

T ( tree( ‘*’, tree (‘+’, tree (‘A’, empty, empty), tree (‘B’, empty, empty) ),
tree (‘–’, tree (‘C’, empty, empty), tree (‘D’, empty, empty) )
)
)

showing clearly the PRINTed output and the values of the parameter
omitted from the table (rows 4, 5, 6, 7) for the seven calls of T.

Call Parameter
Number

1 tree(‘*’, tree(‘+’, tree(‘A’,empty,empty), tree(‘B’,empty,empty) ),


tree(‘–’, tree(‘C’,empty,empty), tree(‘D’,empty,empty) )
)

2 tree(‘ +’, tree(‘A’,empty,empty), tree(‘B’,empty,empty) )

3 tree(‘A’,empty,empty)

7
(10)

(f) What tree traversal algorithm does procedure T describe?

Page 23 of 24
___________________________________________________________________

___________________________________________________________________
(1)
(Total 20 marks)

Page 24 of 24

You might also like