扁平化多级双向链表
多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。

#include <iostream> #include <stack> #include <queue> using namespace std; class Node { public: int val; Node *prev; Node *next; Node *child; }; class Solution { public: Node *flatten(Node *head) { if (!head) return nullptr; Node *new_head = new Node(); Node *now = new_head; stack<Node *> st; st.push(head); while (!st.empty()) { Node *cur = st.top(); st.pop(); cur->prev = now; now->next = cur; if (cur->next) st.push(cur->next); if (cur->child) st.push(cur->child); now = now->next; now->child = nullptr; } now->next = nullptr; new_head->next->prev = nullptr; return new_head->next; } };
浙公网安备 33010602011771号