zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 430 扁平化多级双向链表

    430. 扁平化多级双向链表

    您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。

    扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。

    示例:

    输入:

     1---2---3---4---5---6--NULL
             |
             7---8---9---10--NULL
                 |
                 11--12--NULL
    

    输出:
    1-2-3-7-8-11-12-9-10-4-5-6-NULL

    以上示例的说明:

    给出以下多级双向链表:

    在这里插入图片描述

    我们应该返回如下所示的扁平双向链表:

    在这里插入图片描述

    /*
    // Definition for a Node.
    class Node {
        public int val;
        public Node prev;
        public Node next;
        public Node child;
    
        public Node() {}
    
        public Node(int _val,Node _prev,Node _next,Node _child) {
            val = _val;
            prev = _prev;
            next = _next;
            child = _child;
        }
    };
    */
    class Solution {
    //   public Node flatten(Node head) {
    //     if (head == null) return head;
    //     Node pseudoHead = new Node(0, null, head, null);
    
    //     flattenDFS(pseudoHead, head);
    
    //     pseudoHead.next.prev = null;
    //     return pseudoHead.next;
    //   }
    //   public Node flattenDFS(Node prev, Node curr) {
    //     if (curr == null) return prev;
    //     curr.prev = prev;
    //     prev.next = curr;
    
    //     Node tempNext = curr.next;
    
    //     Node tail = flattenDFS(curr, curr.child);
    //     curr.child = null;
    
    //     return flattenDFS(tail, tempNext);
    //   }
    
     public Node flatten(Node head) {
        if (head == null) return head;
    
        Node pseudoHead = new Node(0, null, head, null);
        Node curr, prev = pseudoHead;
    
        Deque<Node> stack = new ArrayDeque<>();
        stack.push(head);
    
        while (!stack.isEmpty()) {
          curr = stack.pop();
          prev.next = curr;
          curr.prev = prev;
    
          if (curr.next != null) stack.push(curr.next);
          if (curr.child != null) {
            stack.push(curr.child);
            // don't forget to remove all child pointers.
            curr.child = null;
          }
          prev = curr;
        }
        // detach the pseudo node from the result
        pseudoHead.next.prev = null;
        return pseudoHead.next;
      }
     
    
    }
    
  • 相关阅读:
    django http请求request详解
    HTTP协议向服务器传参
    股票交易费用及复利计算公式
    scrapy初步使用
    通过 multiprocessing Pool 线程池加速爬虫的处理
    通过 PIL 和 Python-tesseract 模拟登陆
    BeautifulSoup
    xpath
    http 请求特殊字符
    HTTP cookies
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075692.html
Copyright © 2011-2022 走看看