Sei sulla pagina 1di 3

Excercise 3

Hoang Nguyen d117721, Huy Nguyen d117724, Rao Moueed Ahmed d119447
September 27, 2020

1 Exercise 14
Algorithm 1: Join(Q1, Q2):
while Q2 is not empty do
item = Q2.pop();
Q1.push(item);
return Q1;

2 Exercise 15
Algorithm 2: Reverse(Q):
Declare a stack S;
while Q is not empty do
item = Q.pop();
S.push(item);
while S is not empty do
item = S.pop();
Q.push(item);
return Q;

1
3 Exercise 16
Algorithm 3: Josephus(M, N ):
Declare a Node head;
head.key = 1;
prev = head;
for i from 2 to n do
prev.next = a new Node;
prev.next.key = i;
prev = prev.next;
prev.next = head;
pointer1 = pointer2 = head;
while pointer1.next 6= pointer2 do
count = 1;
while count < N do
pointer2 = pointer1;
pointer1 = pointer1.next;
count + +;
pointer2.next = pointer1.next;
pointer1 = pointer2.next;
return pointer1.key
After N time of movement, the number of people on table decreases by 1, but we need keep
procedure works until only 1 person left, so the number of movement is M N . Order of magnitude
of the time required is O(M N )

4 Exercise 17
Algorithm 4: Swap(m, L):
if m = 1 then
temp = L.head;
L.head = L.head.next;
temp.next = L.head.next;
L.head.next = temp;
else
current = L.head.next;
prev = L.head;
count = 1;
while count < m do
prev = current;
current = current.next;
temp = current;
temp.next = current.next.next;
prev.next = current.next;
current.next.next = temp;
return L

5 Exercise 18
a) Postfix: a b + c * d +
Prefix: + * + a b c d

2
b) Postfix: a b * c * d + e *
Prefix: * + * * a b c d e
c)Postfix: a e / b + d e * c + *
Prefix: * + / a e b + * d e c

6 Exercise 19
We can statically allocate an array of nodes, then we can use integer to indicate the ”previous” and ”next ”
values for each nodes without using pointers. Specifically, we can define a class as a node with 3 attributes :
data, and 2 integer variables prev and next which are the index of the previous and next Nodes in the list.
Without using object references, when we add and remove an item from the list, we have to update prev
and next of all other nodes, which means it can be performed in linear time.

Potrebbero piacerti anche