@@ -4,18 +4,26 @@ public class App {
4
4
5
5
public static int get (LinkedList list , int index ) {
6
6
LinkedList .Node item = list .head ; // O(1)
7
- for (int i = 0 ; i < index ; i ++) { // O(n)
7
+ int length = list .length ();
8
+ for (int i = 0 ; i < length ; i ++) { // O(n)
9
+ if (i ==index ){
10
+ return item .data ;
11
+ } // This would make it so that if index is in the bounds of length then it will return the data other wise return null right?
8
12
item = item .next ; // O(1)
13
+
9
14
}
10
15
return item .data ; // O(1)
11
16
} // Algorithmic Complexity = O(n)
12
17
13
18
public static void set (LinkedList list , int index , int value ) {
14
19
LinkedList .Node item = list .head ; // O(1)
15
- for (int i = 0 ; i < index ; i ++) { // O(n)
20
+ int length = list .length ();
21
+ for (int i = 0 ; i < length ; i ++) { // O(n)
22
+ if (i ==index ){
23
+ item .data = value ;
24
+ }
16
25
item = item .next ; // O(1)
17
26
}
18
- item .data = value ; // O(1)
19
27
} // Algorithmic Complexity = O(n)
20
28
21
29
public static void remove (LinkedList list , int index ) {
@@ -35,14 +43,24 @@ public static void remove(LinkedList list, int index) {
35
43
} // Algorithmic Complexity = O(n)
36
44
37
45
public static LinkedList reverse (LinkedList list ) {
38
- LinkedList reversedList = new LinkedList (); // O(1)
46
+ // LinkedList reversedList = new LinkedList(); // O(1)
47
+ // LinkedList.Node item = list.head; // O(1)
48
+ // int length = list.length();
49
+ // for (int i = 0; i < length; i++) { // O(n)
50
+ // reversedList.prepend(item.data); // O(1)
51
+ // item = item.next; // O(1)
52
+ // }
53
+ // return reversedList; // O(1)
39
54
LinkedList .Node item = list .head ; // O(1)
40
-
41
- for (int i = 0 ; i < list .length (); i ++) { // O(n)
42
- reversedList .prepend (item .data ); // O(1)
55
+ int length = list .length ();
56
+ int counter = 0 ;
57
+ for (int i = 0 ; i < length ; i ++) { // O(n)
58
+ list .prepend (item .data ); // O(1)
59
+ counter ++;
60
+ remove (list , counter );
43
61
item = item .next ; // O(1)
44
62
}
45
- return reversedList ; // O(1)
63
+ return list ; // O(1)
46
64
} // Algorithmic Complexity = O(n)
47
65
48
66
public static boolean isSortedAscending (LinkedList list ) {
0 commit comments