[英]How to segregate a linked list into two other lists, one with odd indices the other one with even indices but in recursion way
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.该问题要求编写一个 function,它可以将链表拆分为另外两个列表,一个具有奇数索引,另一个具有偶数索引但递归。 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.?你能帮我写那个 function 来完成这项工作吗?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.