430. Flatten a Multilevel Doubly Linked List 發表於 2023-02-13 | 分類於 leetcode problemsolution1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/*// Definition for a Node.class Node {public: int val; Node* prev; Node* next; Node* child;};*/class Solution {public: Node* flatten(Node* head) { if(!head) return head; stack<Node *> sta; Node *p = head; // iterative //flatten linked list while(p->next || p->child){ if(p->child){ sta.push(p->next); p->next = p->child; p->child = nullptr; } p=p->next; } while(!sta.empty()){ Node *next = sta.top(); sta.pop(); p->next = next; while(p->next) p=p->next; } p=head; // build bi-direct connection while(p->next){ p->next->prev = p; p=p->next; } p->next = nullptr; return head; }}; analysis time complexity O(n) space complexity O(n)