|
3 | 3 | public class App {
|
4 | 4 |
|
5 | 5 | public static int get(LinkedList list, int index) {
|
6 |
| - return 0; |
7 |
| - } |
| 6 | + LinkedList.Node item = list.head; // O(1) |
| 7 | + for (int i = 0; i < index; i++) { // O(n) |
| 8 | + item = item.next; // O(1) |
| 9 | + } |
| 10 | + return item.data; // O(1) |
| 11 | + } // Algorithmic Complexity = O(n) |
8 | 12 |
|
9 |
| - public static void set(LinkedList list, int index, int value) {} |
| 13 | + public static void set(LinkedList list, int index, int value) { |
| 14 | + LinkedList.Node item = list.head; // O(1) |
| 15 | + for (int i = 0; i < index; i++) { // O(n) |
| 16 | + item = item.next; // O(1) |
| 17 | + } |
| 18 | + item.data = value; // O(1) |
| 19 | + } // Algorithmic Complexity = O(n) |
10 | 20 |
|
11 |
| - public static void remove(LinkedList list, int index) {} |
| 21 | + public static void remove(LinkedList list, int index) { |
| 22 | + |
| 23 | + LinkedList.Node item = list.head; // O(1) |
| 24 | + if (index == 0) { // O(1) |
| 25 | + list.head = list.head.next; // O(1) |
| 26 | + } |
| 27 | + for (int i = 0; i < index - 1; i++) { // O(n) |
| 28 | + item = item.next; // O(1) |
| 29 | + } |
| 30 | + if (item.next.next == null) { // O(1) |
| 31 | + item.next = null; // O(1) |
| 32 | + } else { // O(1) |
| 33 | + item.next = item.next.next; // O(1) |
| 34 | + } |
| 35 | + } // Algorithmic Complexity = O(n) |
12 | 36 |
|
13 | 37 | public static LinkedList reverse(LinkedList list) {
|
14 |
| - return list; |
15 |
| - } |
| 38 | + LinkedList reversedList = new LinkedList(); // O(1) |
| 39 | + 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) |
| 43 | + item = item.next; // O(1) |
| 44 | + } |
| 45 | + return reversedList; // O(1) |
| 46 | + } // Algorithmic Complexity = O(n) |
16 | 47 |
|
17 | 48 | public static boolean isSortedAscending(LinkedList list) {
|
18 |
| - return false; |
19 |
| - } |
| 49 | + LinkedList.Node item = list.head; // O(1) |
| 50 | + while (item.next != null) { // O(n) |
| 51 | + if (item.data < item.next.data) { // O(1) |
| 52 | + item = item.next; // O(1) |
| 53 | + } else { // O(1) |
| 54 | + return false; // O(1) |
| 55 | + } |
| 56 | + } |
| 57 | + return true; // O(1) |
| 58 | + } // Algorithmic Complexity = O(n) |
| 59 | + |
| 60 | + // Linked List practice |
| 61 | + // Write .get |
| 62 | + // Write .set |
| 63 | + // Write method to delete index |
| 64 | + // Reverse linked list |
| 65 | + // Is linked list sorted? |
| 66 | + // Find algorithmic complexity of each solution |
20 | 67 |
|
21 | 68 | private App() {}
|
22 | 69 | }
|
0 commit comments