在java中展平列表

时间:2015-06-20 05:38:26

标签: java algorithm list

我在接受采访时被问到这个问题

  

给出java中的假设列表,以及保持整数   内容,也可以包含另一个相似类型的列表

示例:[1,3,5,[6,7],8,9,10,[11,13,15,[16,17,[18,19]]],20]

输出应为:

[1,3,5,6,7,8,9,10,11,13,15,16,17,18,19,20]

我很容易想到!所以我带来了解决问题的递归解决方案!或者不是?

采访者说子列表可以深入到任何深度,因此可能导致堆栈溢出错误!

我尝试提出非递归解决方案,但无法解决。谁能告诉非递归解决方案可能是什么?

4 个答案:

答案 0 :(得分:11)

您可以将LinkedList用作堆栈。

public static List<Object> flattenNonRecursive(List<Object> list) {
    List<Object> result = new ArrayList<>();
    LinkedList<Object> stack = new LinkedList<>(list);
    while (!stack.isEmpty()) {
        Object e = stack.pop();
        if (e instanceof List<?>)
            stack.addAll(0, (List<?>)e);
        else
            result.add(e);
    }
    return result;
}

public static List<Object> list(Object... args) {
    return Arrays.asList(args);
}

public static void main(String[] args) {
    List<Object> list = list(1, 3, 5, list(6, 7), 8, 9, 10, list(11, 13, 15, list(16, 17, list(18, 19))), 20);
    System.out.println("flatten=" + flattenNonRecursive(list));
}

结果

flatten=[1, 3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 17, 18, 19, 20]

答案 1 :(得分:4)

这是一个迭代的Java实现(部分基于sarvesh的回答):

import java.util.*;

import static java.util.Arrays.asList;

public class Main {
    public static void main(String[] ars) {
        List<Object> list = asList(asList(1, 2), 3, 4, asList(5, asList(6, 7)));

        System.out.println(flatten(list));
    }

    public static List<Integer> flatten(Iterable<Object> list) {
        List<Integer> result = new ArrayList<Integer>();
        Deque<Iterator> deque = new ArrayDeque<Iterator>();
        deque.add(list.iterator());

        while (!deque.isEmpty()) {
            Iterator it = deque.pop();

            while (it.hasNext()) {
                Object obj = it.next();
                if (obj instanceof Iterable) {
                    deque.push(it);
                    it = ((Iterable) obj).iterator();
                } else if (obj instanceof Integer) {
                    result.add((Integer) obj);
                }
            }
        }
        return result;
    }

}

答案 2 :(得分:2)

您可以对列表中的每个元素使用DFS(深度优先搜索)过程。以下是wiki的示例代码

1  procedure DFS-iterative(G,v):
2      let S be a stack
3      S.push(v)
4      while S is not empty
5            v = S.pop() 
6            if v is not labeled as discovered:
7                label v as discovered
8                for all edges from v to w in G.adjacentEdges(v) do
9                    S.push(w)

答案 3 :(得分:0)

您可以使用以下类型的算法

    public List<?> flatten(List<?> source) {
        List<?> currentSource = source;
        List<Object> flattenedList = new ArrayList<Object>();
        boolean loop = true;
        while (loop) {
            loop = false;
            for (Object item : currentSource) {
                if (item instanceof Collection<?>) {
                    flattenedList.addAll((Collection<?>) item);
                    loop = true;
                } else {
                    flattenedList.add(item);
                }
            }
            if (loop) {
                currentSource = flattenedList;
                flattenedList = new ArrayList<Object>();
            }
        }

        return flattenedList;
    }