leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0430.cpp (834B)


      1 class Solution {
      2     void insert_after(Node **t, Node *n) {
      3         n->prev = *t;
      4         n->child = nullptr;
      5         (*t) = (*t)->next = n;
      6     }
      7 
      8   public:
      9     Node *flatten(Node *head) {
     10         if (!head) return nullptr;
     11 
     12         stack<Node *> s;
     13         s.push(head);
     14 
     15         Node *h, *t;
     16         t = h = new Node();
     17         while (!s.empty()) {
     18             Node *self = s.top();
     19             s.pop();
     20             if (self->next) s.push(self->next);
     21             Node *child = self->child;
     22             insert_after(&t, self);
     23             while (child) {
     24                 self = child;
     25                 child = self->child;
     26                 insert_after(&t, self);
     27                 if (self->next) s.push(self->next);
     28             }
     29         }
     30         t->next = nullptr;
     31         h->next->prev = nullptr;
     32         return h->next;
     33     }
     34 };