flatten linked list

 

A->B->C->D->E
|
V
M
|
V
N
有right和down的linkedlist,要求更新linkedlist变成A->M->N->B->C->D->E,注意M可以还有right,B也可以有down,
其实就是递归输出。然后我做了一会才做出,之前有个大神的面经里发过,但我没仔细看很后悔。我昨晚发现这tmd不是inorder traversal么

 

// Class to represent a node
    class Node{
        char data;
        Node next, down;

        public Node(char data) {
            this.data = data;
            this.next = null;
            this.down = null;
        }
    }

    // Method to flatten the list
    String flattenList(Node head){
        if (head == null)
            return "";

        // Below lines are written in this manner to increase the code readability. 
        // One may choose to use StringBuilder instead of String to optimize it.
        String result = "";
        result += head.data + " ";
        result += flattenList(head.down);
        result += flattenList(head.next);
        return result;
}

  

posted @ 2017-12-13 01:05  apanda009  阅读(255)  评论(0编辑  收藏  举报