简体   繁体   English

如何将链表分成两个其他列表,一个具有奇数索引,另一个具有偶数索引但以递归方式

[英]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.

相关问题 隔离链接列表中的偶数和奇数节点 - Segregate even and odd nodes in a Linked List 创建两个线程,一个显示奇数,另一个显示偶数 - Create two threads, one display odd & other even numbers 合并两个索引列表以在其他两个列表之间创建1-1映射 - Combine two lists of indices to create a 1-1 mapping between two other lists 如何有效地在一个列表中对两个双链表求和? - How to sum two double linked lists in one list efficiently? 使用两个线程依次使用自定义锁打印号码,其中一个正在打印,而另一个正在打印奇数 - Using custom lock print number in sequence using two threads where one is printing even other is printing odd numbers 从同一个pojo数组创建了两个列表,修改了一个列表,同样的事情也会影响其他列表 - Created two Lists from same pojo array, Modifying one List, same thing affects on other list also 使用递归来反转字符串的偶数索引 - Using recursion to reverse even indices of a String 如何创建合并两个其他列表的列表? - How to create a list that merges two other lists? 从同一个数组创建两个列表,修改一个列表,更改另一个列表 - Created two Lists from same array, Modifying one List, changes the other 合并两个不同的列表一个是wifi类型的另一个是蓝牙类型的 - merge two different lists one is of wifi type other is of bluetooth type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM