In: Computer Science
Below is the solution:
import java.util.*;
class LinkedListNode<E>
{
public E element;
public LinkedListNode<E> next;
}
class LinkedListBox<E>
{
public LinkedListNode<E> head;
public int count = 0;
}
public class Main
{
public static void main(String[] args) {
int number = 0;
LinkedListNode<Integer> node = null;
LinkedListBox<Integer> myLinkedList = new
LinkedListBox<Integer>();;
LinkedListNode lastNode = null;
int max = 20; int min = 1;
System.out.println("Enter the number of random
integers to create");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
//Random number generation code
for(int i=0; i < number; i++){
node = new LinkedListNode<Integer>();
int element =
(int)(Math.random()*(max-min+1)+min);
node.element = element;
node.next = null;
//Checking if the head is present or not
if (myLinkedList.head ==
null){
myLinkedList.head = node;
myLinkedList.count++;
//lastNode = node;
}
else{
LinkedListNode tmpNode =
myLinkedList.head;
while(tmpNode.next != null){
tmpNode = tmpNode.next;
}
tmpNode.next = node;
myLinkedList.count++;
}
}
System.out.println("Displaying the Linked List :
");
LinkedListNode tmpNode = myLinkedList.head;
//looping through the List and printing the elements
while(tmpNode.next != null){
System.out.print(tmpNode.element + "->");
tmpNode = tmpNode.next;
}
System.out.println(tmpNode.element);
System.out.println("Removing the even numbers from
Linked List ");
tmpNode = myLinkedList.head;
LinkedListNode prevNode = null;
//Checking if the head value is even or not
while(tmpNode != null && (Integer)tmpNode.element % 2 ==
0){
myLinkedList.head = tmpNode.next;
tmpNode = tmpNode.next;
}
tmpNode = tmpNode.next;
prevNode = myLinkedList.head;
while (tmpNode != null )
{
//checking the node value is even or not
if ((Integer)tmpNode.element % 2 != 0){
prevNode = tmpNode;
tmpNode = tmpNode.next;
}
else {
//Removing the node if the value is even.
prevNode.next = tmpNode.next;
tmpNode = tmpNode.next;
}
}
System.out.println("Displaying the Linked Listafter removing the
even elements : ");
tmpNode = myLinkedList.head;
while(tmpNode.next != null){
//printing the values after removing the even numbers.
System.out.print(tmpNode.element + "->");
tmpNode = tmpNode.next;
}
System.out.println(tmpNode.element);
}
}