欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 430. Flatten a Multilevel Doubly Linked List

程序员文章站 2022-03-04 19:05:34
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 430. Flatten a Multilevel Doubly Linked List

2. Solution

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

    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) {
        stack<Node*> nodes;
        Node* current = head;
        Node* pre = nullptr;
        while(current) {
            if(current->child) {
                if(current->next) {
                    nodes.push(current->next);
                }
                current->next = current->child;
                current->next->prev = current;
                current->child = nullptr;
            }
            pre = current;
            current = current->next;
            if(!current && !nodes.empty()) {
                Node* temp = nodes.top();
                nodes.pop();
                pre->next = temp;
                temp->prev = pre;
                current = temp;
            }
        }
        return head;    
    }
};

Reference

  1. https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/
相关标签: Leetcode