The question asked to write a function that can split a linked list into two other lists, one with odd indices the other one with even indices but recursively. I have read all the similar questions in stack overflow, but they did not have recursive way.
Here is my try:
public class LinkedList {
Node head;
static int count = 0;
static LinkedList oddList = new LinkedList();
static LinkedList evenList = new LinkedList();
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public static void split(Node head) {
if (head == null) return;
split(head.next);
if ((++count) % 2 == 0) {
insert(evenList, head.data);
} else
insert(oddList, head.data);
}
This program just do the traverse recursively not the inserting, I do not know how to traverse and insert elements in my two linked list all in recursion .
Could you help me write that function to do that work.?
Pseudocode:
TwoLists splitEvenAndOddIndices(List originalList) {
if (originalList.isEmpty()) {
return two empty lists;
}
Element head = remove the head (the frontmost element) from originalList;
TwoLists result = splitEvenAndOddIndices(originalList);
Swap the two lists in result;
Prepend head to the first list in result,
return result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.