Uploaded by Kgotso Ntshilane

csi323 LT3 Problems

advertisement
CSI323: Algorithms
University of Botswana
Lecturer: T.Z. Nkgau
August 31, 2023
Problem Set LT3
Problems - Elementary Data Structures
1. Assume the following class declarations.
Figure 1: The Node class and a singly linked lists
(a) What does MYSTERY(head) return? What does the algorithm do in general?
MYSTERY(f irst)
1 if f irst == nil
2
return 0
3 else
4
return 1 + MYSTERY(f irst.next)
Figure 2: Fun with linked lists.
(b) What does MYST(head) do?
MYST(f irst)
1 if f irst.next ̸= nil
2
MYST(f irst.next)
3
Print f irst.key
Figure 3: Fun with linked lists.
(c) What does POINTERS(head) do?
(d) Design an algorithm that given two references to different singly linked lists, concatenates
them by attaching one to the end of the other one.
2
Problem Set LT3: Problems - Elementary Data Structures
POINTERS(f irst)
1 p = nil
2 c = f irst
3 f = f irst
4 while c ̸= nil
5
f = f.next
6
c.next = p
7
p=c
8
c=f
9 return p
Figure 4: Fun with linked lists.
2. A Queue data type stores a sequence of elements. However, insertion is only done at the
rear (bac) of the sequence and deletion is done at the front of the sequence. In other words,
access is in a first-in first-out (FIFO) manner. Observe that the stack data type on the other
hand uses last-in first-out (LIFO) mechanism. The functionality of the Queue data type is
specified by the following the following API.
public class Queue<E>
Queue()
boolean enqueue(E item)
E dequeue()
boolean isEmpty()
int size()
Create an empty queue data structure
Add the item at the back of the queue. Return true if successful.
Get the item at the front.
Return true if the queue has 0 items.
Return the number of items in the queue.
Implement the Queue data type using a doubly linked list. Note that it is far easier if you
keep two references as instance variables: one for the first node and the other for the last
node.
3. Show how to implement a Queue with two stacks. Note that, this means that instead of
implementing a Queue with, say a linked list as above, we use two stack instance variables as
our storage.
Download