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;
}
};