美文网首页facebook 面经
fb 电面 展开层级链表

fb 电面 展开层级链表

作者: Anseis | 来源:发表于2018-09-14 11:30 被阅读0次

都是O(n)
第一种逐层

1->2->11->12
   |
   3->4->5
      |
      6->7
1-2-11-12->3-4-5->6-7
  static void flattenList(Node node) { 
          
        /*Base case*/
        if (node == null) { 
            return; 
        } 
          
        Node tmp = null; 
  
        /* Find tail node of first level linked list */
        Node tail = node; 
        while (tail.next != null) { 
            tail = tail.next; 
        } 
  
       
        // linked list till we reach the tail node 
        Node cur = node; 
        while (cur != tail) { 
  
            // If current node has a child 
            if (cur.child != null) { 
  
                // then append the child at the end of current list 
                tail.next = cur.child; 
  
                // and update the tail to new last node 
                tmp = cur.child; 
                while (tmp.next != null) { 
                    tmp = tmp.next; 
                } 
                tail = tmp; 
                cur.child = null;
            } 
  
            // Change current node 
            cur = cur.next; 
        } 
    } 
 

第二种中间插入,使用栈

1->2->11->12
   |
   3->4->5
      |
      6->7

1-2-3-4-6-7-5-11-12
static void flattenList(Node node) { 
    if (node == null) {
      return null;
    }
    Stack<Node> st = new Stack<>();
    Node cur = node;
    while (cur != null) {
      if (cur.child != null) {
        Node child = cur.child;
        cur.child = null;
        st.push(cur.next);
        cur.next = child;  
      } 
      if (cur.next == null && !st.isEmpty()) {
        cur.next = st.pop();
      }
      cur = cur.next;
    }  
  } 

相关文章

  • fb 电面 展开层级链表

    都是O(n)第一种逐层 第二种中间插入,使用栈

  • FB 电面面经

    a----abbbbc -> ++++++++++c 把所有连续相同字母改成加号 同时dash 两侧如果有相同字符...

  • InnoDB 索引

    链表 -> 二叉查找树 -> 平衡二叉树 -> B树 -> B+树 链表:层级等于链表长度二叉查找树:链表优化,...

  • LeetCode-114-二叉树展开为链表

    二叉树展开为链表 题目描述:给你二叉树的根结点 root ,请你将它展开为一个单链表:展开后的单链表应该同样使用 ...

  • xiaonanan哈密顿回路篇

    杭电 3018father[fa]=fb,写成father[a]=fb;难受,是真的难受弄错了,搞了我几个小时,还...

  • UITableView 多层级(树形)展开

    先看一下效果图! 最近项目中遇到多层级Cell 展开的功能,于是就把这些总结了一下,代码详见Demo,这里写了两种...

  • 114. 二叉树展开为链表

    二叉树展开为链表给定一个二叉树,原地将它展开为链表。 例如,给定二叉树

  • 114. 二叉树展开为链表

    题目:给你二叉树的根结点 root ,请你将它展开为一个单链表: 展开后的单链表应该同样使用 TreeNode ,...

  • 114. 二叉树展开为链表

    给你二叉树的根结点 root ,请你将它展开为一个单链表: 展开后的单链表应该同样使用 TreeNode ,其中 ...

  • 二叉树展开为链表 2022-03-03 周四

    题目 给你二叉树的根结点 root ,请你将它展开为一个单链表: 展开后的单链表应该同样使用 TreeNode ,...

网友评论

    本文标题:fb 电面 展开层级链表

    本文链接:https://www.haomeiwen.com/subject/nxfogftx.html