leetcode430. Flatten a Multilevel Doubly Linked List

https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/

每个节点不仅有next还有child。根据便利顺序可以看到child是先遍历的,next后遍历。所以把next先入栈。如果有child再把child入栈。这样就能保证child先于next遍历。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* prev;
    Node* next;
    Node* child;

    Node() {}

    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) return NULL;
        stack<Node*> stk;
        stk.push(head);
        Node* pre = NULL;
        while(!stk.empty())
        {
            Node* cur = stk.top(); stk.pop();
            if(cur->next) stk.push(cur->next);
            if(cur->child)
            {
                stk.push(cur->child);
                cur->child = NULL;
            }
            if(pre)
            {
                pre->next = cur;
                cur->prev = pre;
            }
            pre = cur;
        }
        return head;
    }
};
发布了44 篇原创文章 · 获赞 0 · 访问量 956

猜你喜欢

转载自blog.csdn.net/weixin_37748689/article/details/102756682