I am trying to solve this question : "Arrange elements in a given Linked List such that, all even numbers are placed after odd numbers. Respective order of elements should remain same."
This is the code I am using :
class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
This is the main logic :
static Node<Integer> sortOddEven(Node<Integer> head) {
if(head == null || head.next == null) {
return head;
}
Node<Integer> middle = getMiddle(head);
Node<Integer> nextOfMiddle = middle.next;
middle.next = null;
Node<Integer> temp1 = sortOddEven(head);
Node<Integer> temp2 = sortOddEven(nextOfMiddle);
Node<Integer> sortedList = sortOddEvenMerger(temp1, temp2);
return sortedList;
}
static Node<Integer> sortOddEvenMerger(Node<Integer> head1, Node<Integer> head2) {
Node<Integer> head3 = null, tail3 = null;
if(head1.data.intValue()%2 != 0) {
head3 = head1;
tail3 = head1;
head1 = head1.next;
} else {
head3 = head2;
tail3 = head2;
head2 = head2.next;
}
while(head1 != null || head2 != null) {
if(head1 == null) {
tail3.next = head2;
return head3;
} else if(head2 == null){
tail3.next = head1;
return head3;
}
if(head1.data.intValue()%2 != 0) {
tail3.next = head1;
tail3 = tail3.next;
head1 = head1.next;
} else {
tail3.next = head2;
tail3 = tail3.next;
head2 = head2.next;
}
}
tail3.next = null;
return head3;
}
Basically I have tweaked MergeSort
algorithm a little bit to solve this one, if I encounter odd elements , I add them first in the sortOddEvenMerger
method and even elements after them. But the relative order of elements get changed.
Example : Input - 1 4 5 2
Expected output - 1 5 4 2
My output - 1 5 2 4
How can I tweak it more to maintain the relative order?
O(1)
if you maintain a reference to the lastNode
in the odd list and the head of the even list?oddCurrent.next = evenHead
(of course checks should be added to ensureoddCurrent != null
, which is possible). I guess judging by what you saidO(n)
was a typo. – Cohere