Delete all prime nodes from a singly linked list in java
Java program for Delete all prime nodes from a singly linked list. Here problem description and explanation.
// Java Program for
// Delete all prime nodes in linked list
// Linked list node
class LinkNode
{
public int data;
public LinkNode next;
public LinkNode(int data)
{
this.data = data;
this.next = null;
}
}
public class SingleLL
{
public LinkNode head;
public SingleLL()
{
// Set inital value
this.head = null;
}
// Add new node at the end of linked list
public void addNode(int value)
{
// Create node
LinkNode node = new LinkNode(value);
if (this.head == null)
{
this.head = node;
}
else
{
LinkNode temp = this.head;
// Find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
// Add node at last position
temp.next = node;
}
}
// Display all Linked List elements
public void display()
{
if (this.head != null)
{
LinkNode temp = this.head;
while (temp != null)
{
// Display node value
System.out.print(" " + temp.data);
// Visit to next node
temp = temp.next;
}
}
else
{
System.out.print("Empty Linked list\n");
}
}
// Return given value is prime or not
public boolean checkPrime(int value)
{
if (value == 1)
{
return false;
}
else
{
for (int i = 2; i <= value / 2; i++)
{
// Check whether value is prime or not
if (value % i == 0)
{
return false;
}
}
return true;
}
}
public void delelePrimeNode()
{
if (this.head == null)
{
System.out.println("Empty linked List");
}
else
{
int remove = 0;
// Auxiliary variables
LinkNode temp = this.head;
LinkNode hold = null;
LinkNode prev = null;
// Iterating and find prime nodes
while (temp != null)
{
if (this.checkPrime(temp.data))
{
// Is prime node
hold = temp;
}
else
{
prev = temp;
}
// Visit to next node
temp = temp.next;
if (hold != null)
{
if (hold == this.head)
{
// When delete head node
this.head = temp;
hold = null;
}
else
{
if (prev != null)
{
prev.next = temp;
}
hold = null;
}
}
}
}
}
public static void main(String[] args)
{
SingleLL sll = new SingleLL();
// Linked list
// 7 → 1 → 8 → 2 → 4 → 23 → 37 → NULL
sll.addNode(7);
sll.addNode(1);
sll.addNode(8);
sll.addNode(2);
sll.addNode(4);
sll.addNode(23);
sll.addNode(37);
System.out.println(" Before Delete prime nodes ");
sll.display();
sll.delelePrimeNode();
System.out.println("\n After Delete prime nodes ");
sll.display();
}
}
Output
Before Delete prime nodes
7 1 8 2 4 23 37
After Delete prime nodes
1 8 4
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment