Problem
Given a singly linked list, split it into two linked lists. These linked lists will contain the alternate nodes from the given linked list.
Examples
Example 1:
head = [1,2,3,4,5]
Output: [[1, 3, 5], [2, 4]]
Solution
Method 1 - Iterative
To solve the problem of splitting a singly linked list into two linked lists containing alternate nodes, you can use the following approach in Java:
- Initiate 2 head pointers -
head1
andhead2
and 2 iterating pointers -curr1
andcurr2
. - Now traverse the original list adding the nodes to lists in an alternating way.
- Ensure that after the loop, both
curr1.next
andcurr2.next
point to null to terminate the lists correctly.
Code
Java
public class Solution {
public ListNode[] splitAlternatingNodes(ListNode head) {
// Edge case: If the head is null or there's only one node, handle accordingly
if (head == null || head.next == null) {
return new ListNode[] {
head, null
};
}
// Pointers for the two new linked lists
ListNode head1 = head;
ListNode head2 = head.next;
ListNode curr1 = head1;
ListNode curr2 = head2;
ListNode curr = head.next.next;
boolean addToFirst = true; // To alternate between the two lists
while (curr != null) {
if (addToFirst) {
curr1.next = curr;
curr1 = curr1.next;
} else {
curr2.next = curr;
curr2 = curr2.next;
}
curr = curr.next;
addToFirst = !addToFirst; // Switch the boolean
}
// Ensure the last nodes point to null
curr1.next = null;
curr2.next = null;
return new ListNode[] {
head1, head2
};
}
}