1. 程式人生 > >430 扁平化多級雙向連結串列

430 扁平化多級雙向連結串列

Node *flatten(Node *head) {
    Node *it = head;
    stack<Node *> stack1;
    while (it) {
        if (it->child) {
             stack1.push(it->next);
                it->next = it->child;
                it->child->prev = it;
                it->child = nullptr;
            } else if (!it->next && !stack1.empty()) {
                it->next = stack1.top();
                if (it->next)
                    it->next->prev = it;
                stack1.pop();
            }
            it = it->next;
        }
        return head;
    }