Comp201 Tut
Comp201 Tut
1 2 3 4 5
Add element
1 2 Element 3 4 5
+1 +1 +1
A LinkedList is a linked data structure were every element
(except the last) has reference to the next element in the
list. To add the element at a given index, p, involves
making the element at p-1, point to the new element
which was at index p. Involve few operations com[pared to
arraylist.
|
8. a. Set1.addAll(set2);
- “red”, “yellow”, ”green”, “blue” : set1
- “red”, “yellow”, “blue” : set2
b. Set1.add(set2);
- Set1: (Red, yellow, green[“red”, “yellow”, “blue”]
c. Set1.RemoveAll(set2)
- Set1: “green”
d. Set1.Remove(set2)
- [red, yellow, green] – set1
- [red, yellow, blue] – set2
e. Set1.RetainAll(set2)
- Set1: “red”, “yellow”
f. set.clear();
- set1: [] – empty
c. O(n).
10.
a. Bubble sort – O(n2)
11.
Outer loop i | 1 3 9 … n (i≤ n)
k
Inner loop | 1 3 9 … 3
Executed i times
T(n) = 30 + 31 + 32 + …. + 3k
k+1
3 −1
n = 3k
3−1
k = log3n
1
= 3k+1 – 2
1
= 3log3n-+1 - 2
1 1
= 3log3n * 3 2 - 2
T(n) = O(n)
12. a.
@Override
public int compareTo(RealNumber other) {
if (this.i != other.i) {
return Integer.compare(this.i, other.i);
} else {
return Double.compare(this.f, other.f);
}
}
b.
public class CompareF implements Comparator<RealNumber>
{
@Override
public int compare(RealNumber rn1, RealNumber rn2) {
// Compare the f-components first
int result = Double.compare(rn1.getF(), rn2.getF());
b. Checks if the list only has one node, making the empty
by setting
head, tail to null and element removed & returned.
c. Purpose is to traverse the elements in a doubly linked
list to reach
second-to-last node (node before tail)
d.
public E removeNode() {
if (head == null) {
return null;
} else if (head.next == null) {
DLLNode<E> temp = head;
head = tail = null;
size--;
return temp.element;
} else {
DLLNode<E> temp = tail;
tail = tail.prev;
tail.next = null;
size--;
return temp.element;
}
}
15. a. IndexSize – 1
16.
1. Enque
public void enqueue (E element) {
arraylist.add(element);
}
2. Dequeue
if (arraylist.isEmpty()) {
return null;
}
int highest = 0;
for (int i = 0; i < arrayList.Size(); i++){
if (arrayList.get(i).compareTo()){
if (arrayList.highestP > 0){
highest = c;
}
}
}