1. Create a linked list using the Node class that contains the first million prime numbers (primes4.txt). It should have a menu with these options:
1 = Search for a Number (let the user enter a number to search
for)
2 = Add a new Number (let the user enter a number and add it to the
head of the list)
3 = Delete a Number (let the user enter a number and delete it if
found)
4 = Exit
class Node
{
int Data;
Node Next;
// you may want to also create a constructor that
takes the Data as a parameter
Node()
{
Next = null;
}
}
Code
import java.io.*;
import java.util.*;
class Node
{
int Data;
Node Next;
// you may want to also create a constructor that takes the Data
as a parameter
Node()
{
Next = null;
}
}
public class LinkedList
{
public static void main (String[] args) throws IOException
{
File file = new File("primes4.txt");
Scanner infile = new Scanner(file);
Scanner in = new Scanner(System.in);
Node Head = null; // Head is the start of the linked list
Node Temp, Previous; // Temp and Previous are used to delete an
item from the list
int Count = 0;
// Read in primes4.txt and add each item to the linked
list
int A;
while (infile.hasNextInt())
{
A = infile.nextInt();
Count++;
Temp = new Node();
Temp.Data = A;
Temp.Next = Head;
Head = Temp;
}
System.out.println("Finished reading in " + Count + "
numbers");
int Choice = 0;
while (Choice != 4)
{
printMenu();
System.out.print("Enter your choice: ");
Choice = in.nextInt();
if (Choice == 1)
{
System.out.print("\nEnter number to search for: ");
A = in.nextInt();
Temp = Head;
while (Temp != null && Temp.Data != A)
{
Temp = Temp.Next;
}
if (Temp == null)
System.out.println("Your number was NOT found.");
else
System.out.println("Your number was found!");
}
if (Choice == 2)
{
System.out.println("\nAdd : ");
A = in.nextInt();
Temp = new Node();
Temp.Data = A;
Temp.Next = Head;
Head = Temp;
System.out.println(A +" add to the list");
}
if (Choice == 3)
{
System.out.println("\nEnter number to delete: ");
A = in.nextInt();
Temp = Head;
Previous=Temp;
while (Temp != null && Temp.Data != A)
{
Previous = Temp;
Temp = Temp.Next;
}
if (Temp == null)
System.out.println("Your number was NOT found.");
else
{
System.out.println("Your number was deleted!");
Previous.Next=Temp.Next;
}
}
}
}
private static void printMenu() {
System.out.println("\n1 = Search for a Number (let the user enter a
number to search for)\n" +
"2 = Add a new Number (let the user enter a number and add it to
the head of the list)\n" +
"3 = Delete a Number (let the user enter a number and delete it if
found)\n" +
"4 = Exit");
}
}
you didn't provide the primes4.txt so i just created my on with few numbers
output
prime4.txt
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.
Get Answers For Free
Most questions answered within 1 hours.