通过Collection框架

时间:2017-04-20 15:38:44

标签: data-structures java-8 java-stream

请考虑此示例http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/

我能够通过java中的集合来展平多级链表,但是我无法在给定节点及其子节点和下一个节点之间建立关系。在当前示例中,10具有值为4,20和13的子节点。我想以更好的方式使用Collections框架,它可以指定子节点和下一个节点,然后对给定的输入应用flatten操作。请帮我 。

    List<List<Integer>> obj =new LinkedList<List<Integer>>();
    obj.add(Arrays.asList(10,5,12,7,11));
    obj.add(Arrays.asList(4,20,13,17,6));
    obj.add(Arrays.asList(2,16,9,8));
    obj.add(Arrays.asList(3,19,15));

    obj.stream().flatMap(e->e.stream()).forEach(i->System.out.print(i+" "));;

1 个答案:

答案 0 :(得分:0)

我解决了这里的问题是代码。

 import java.util.*;
import java.lang.*;
import java.io.*;

class Node {
    int data;
    List<Node> child;

    public Node(int data, List<Node> child) {
        this.data = data;
        this.child = child;
    }

    @Override
    public String toString() {
        return data+" ";
    }
}

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
            List<Node> obj1 = new LinkedList<Node>();

        obj1.add(new Node(10, Arrays.asList(new Node(4,null),new Node(20,Arrays.asList(new Node(2, null))),
                new Node(13,Arrays.asList(new Node(16, Arrays.asList(new Node(3, null)))))  )));
        obj1.add(new Node(5, null));
        obj1.add(new Node(12,null));
        obj1.add(new Node(7,Arrays.asList(new Node(17, Arrays.asList(new Node(9, Arrays.asList(new Node(19, null),
                new Node(15, null))),new Node(8, null))
                ),new Node(6, null))
                ));
        obj1.add(new Node(11,null));

        int tail=obj1.size();

        for(int i=0;i<tail;i++)
        {
            Node n=obj1.get(i);
            if(n.child!=null)
            {
                for(Node o:n.child)
                {
                    obj1.add(tail, o);
                    tail++;
                }
                n.child=null;
            }
        }

        System.out.println(obj1);

    }
}