86 lines
2.5 KiB
Java
86 lines
2.5 KiB
Java
package Week6_Lab;
|
|
import java.util.*;
|
|
public class lab6_LL {
|
|
|
|
public static void main(String[] args){
|
|
LinkedList<Integer> ll = new LinkedList<Integer>();
|
|
|
|
ll.add(1);
|
|
ll.add(3);
|
|
ll.add(5);
|
|
ll.add(7);
|
|
ll.add(9);
|
|
ll.add(11);
|
|
|
|
// Question 1
|
|
System.out.print("Before adding: ");
|
|
printLinkedList(ll);
|
|
System.out.print("After adding and sorting: ");
|
|
printLinkedList(addAndSort(ll, 10));
|
|
|
|
// Question 2
|
|
//System.out.print("Before swapping:");
|
|
//printLinkedList(ll);
|
|
System.out.print("After swapping:");
|
|
swap(ll, 1, 6);
|
|
printLinkedList(ll);
|
|
|
|
//Question 3
|
|
LinkedList<Integer> randInt = new LinkedList<Integer>();
|
|
Random rand = new Random();
|
|
System.out.println("The 500 random numbers generated are: ");
|
|
for (int i = 0; i < 500; i++) {
|
|
randInt.add(rand.nextInt(1000, 9999));
|
|
}
|
|
|
|
printLinkedList(randInt);
|
|
|
|
int randomIntegerToSearch = rand.nextInt(1000, 9999);
|
|
System.out.println("\nAnother random number generated is " + randomIntegerToSearch);
|
|
|
|
int index = search(randInt, randomIntegerToSearch);
|
|
System.out.println(index);
|
|
}
|
|
|
|
public static void printLinkedList(LinkedList<Integer> ll){
|
|
System.out.print("[");
|
|
for (Integer integer : ll) {
|
|
if (Objects.equals(integer, ll.getLast())) {
|
|
System.out.println(integer + "]");
|
|
break;
|
|
}
|
|
System.out.print(integer + ", ");
|
|
}
|
|
}
|
|
public static LinkedList<Integer> addAndSort(LinkedList<Integer> ll, int value){
|
|
//ll.add(value);
|
|
//Collections.sort(ll); This Works
|
|
|
|
//Alternative is to loop through the list and insert the value at the correct index
|
|
for (int i = 0; i < ll.size(); i++) {
|
|
if (value < ll.get(i)) {
|
|
ll.add(i, value);
|
|
break;
|
|
}
|
|
}
|
|
|
|
return ll;
|
|
}
|
|
|
|
public static void swap(LinkedList<Integer> ll, int indexOne, int indexTwo){
|
|
int temp = ll.get(indexOne);
|
|
ll.set(indexOne, ll.get(indexTwo));
|
|
ll.set(indexTwo, temp);
|
|
}
|
|
|
|
public static int search(LinkedList<Integer> list, int searchVal){
|
|
for (Integer integer : list) {
|
|
if (integer == searchVal) {
|
|
System.out.println("Found " + searchVal + " at index " + list.indexOf(integer));
|
|
return list.indexOf(integer);
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
}
|