Posted on by Kalkicode
Code Single linked list

# Segregate even and odd nodes in sorted order in java

Java program for Segregate even and odd nodes in sorted order. Here problem description and other solutions.

``````// Java program for
// Segregate even and odd nodes in ascending order
// Linked list node
{
public int data;
{
this.data = data;
this.next = null;
}
}
public class SingleLL
{
public SingleLL()
{
// Set head value
}
// Add new node at the end of linked list
public void insert(int value)
{
// Create  node
if (this.head == null)
{
}
else
{
// 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)
{
while (temp != null)
{
// Display node value
System.out.print("  " + temp.data);
// Visit to next node
temp = temp.next;
}
}
else
{
}
}
{
if (this.head == null)
{
}
else if (this.head.data >= element.data)
{
}
else
{
// Finding location of inserting node
while (temp.next != null &&
temp.next.data < element.data)
{
// Visit to next node
temp = temp.next;
}
element.next = temp.next;
temp.next = element;
}
}
public void segregateNode(SingleLL odd, SingleLL even)
{
LinkNode node = null;

// Iterating the linked list node
while (this.head != null)
{

// Visit to next node

// Set null to next node
node.next = null;

if (node.data % 2 == 0)
{
// When node value is Even
}
else
{
// When node value is Odd
}
}
}
public static void main(String[] args)
{
// Create linked lists
SingleLL sll = new SingleLL();
SingleLL odd = new SingleLL();
SingleLL even = new SingleLL();
// Linked list sll
// 4 → 3 → 5 → 2 → 11 → 1 → 6 → NULL
sll.insert(4);
sll.insert(3);
sll.insert(5);
sll.insert(2);
sll.insert(11);
sll.insert(1);
sll.insert(6);
System.out.println("Initial Element");
// Display all node
sll.display();
sll.segregateNode(odd, even);
System.out.println("\nEven Element");
// Display all even node
even.display();
System.out.println("\nOdd Element");
// Display all odd node
odd.display();
}
}``````

Output

``````Initial Element
4  3  5  2  11  1  6
Even Element
2  4  6
Odd Element
1  3  5  11``````

## Comment

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.

Categories
Relative Post