我如何以递归方式合并两个列表?

时间:2014-10-22 03:11:56

标签: java recursion

我想出了如何以递归方式反转一个列表,但我想弄清楚如何使用递归合并两个列表。

避免使用集合。

这是如何扭转这个名单所做的,但我一直在努力研究如何合并两个,我根本无法弄明白,这就是为什么我要求人们更熟练。

public class Test {

    public static class Node {



            public Node next;
            public String name;

            public Node(String name) {
                    this.name = name;
            }

    }

    public static void reverse(Node previous, Node current) {

        if (current.next != null) {

            Node next= current.next;
            reverse(current, next);
        }

            if (previous == null) {
            // this was the start node
                    current.next= null;
        } else {
            //reverse
            current.next= previous;
        }


    }


    public static void main(String[] args) throws IOException, InterruptedException {

            Node n1= new Node("A");
            Node n2= new Node("B");
            Node n3= new Node("C");
            Node n4= new Node("D");


            n1.next= n2;
            n2.next= n3;
            n3.next= n4;


            Node cursor= n1;
            while (cursor != null) {
                    System.out.println(cursor.name);
                    cursor= cursor.next;
            }


            reverse(null, n1);

            cursor= n4;
            while (cursor != null) {
                    System.out.println(cursor.name);
                    cursor= cursor.next;

我很难过。即使我不配得到满满的答案,我也希望能指出正确的方向。

1 个答案:

答案 0 :(得分:0)

public class Test1 {
    public static void main(String args[]) throws IOException {
        List<Integer> list1 = new ArrayList<Integer>();
        list1.add(2);
        list1.add(5);
        list1.add(8);

        List<Integer> list2 = new ArrayList<Integer>();
        list2.add(1);
        list2.add(4);
        list2.add(9);

        List<Integer> mergeList = mergeList(list1, list2);
        System.out.println(Arrays.asList(mergeList));
    }

    private static List<Integer> mergeList(List<Integer> list1, List<Integer> list2) {
        if (list1.size() == 0)
            return list2;
        if (list2.size() == 0)
            return list1;

        ArrayList result = new ArrayList<Integer>();

        if (list1.get(0) < list2.get(0))// sorting
            result.add(list1.remove(0));
        else
            result.add(list2.remove(0));

        result.addAll(mergeList(list1, list2));

        return result;
    }
}

排序输出

[[1, 4, 9, 2, 5, 8]]