-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh4.txt
executable file
·85 lines (49 loc) · 1.58 KB
/
h4.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Q1:
public void loopFromStart(int startPos) {
listNode<E> startNode = null;
listNode<E> currentNode = null;
startNode = this.get(startPos);
currentNode = startNode.getNext();
System.out.println(startNode.getData());
while(currentNode != startNode) {
System.out.println(currentNode.getData());
currentNode = currentNode.getNext();
}
}
Q2:
(a) Algorithm 1: O(log(N))
Algorithm 2: O(N^2)
Algorithm 3: O(N^2)
(b) Algorithm 1
(c) No, when dealing with small sets using a simpler implementation such as a quadratic forumula over a log formula would be preferable.
Q3: (a)
public static boolean isPalindrome (Listnode<Integer> head, int numItems) {
Listnode<Integer> currentNode;
while(numItems > 0) {
currentNode = head;
for(int i = 0; i<numItems; i++) {
currentNode = currentNode.getNext();
}
if(currentNode.getData() != head.getData()){
return false;
}
numItems = numItems - 2;
head = head.getNext();
}
return true;
}
Time Complexity = O(N^2)
(b)
public static boolean isPalindrome (DblListnode<Integer> head, int numItems) {
DblListnode<Integer> currentNode = head.getPrevious();
while(numItems > 0) {
if(currentNode.getData() != head.getData()){
return false;
}
currentNode = currentNode.getPrevious();
head = head.getNext();
numItems = numItems - 2;
}
return true;
}
Time Complexity = O(N) Regardless of the size of the list, it always only goes through once. Therefore, the time it takes is linearly dependent on the size of the list.