码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 430. Faltten a Multilevel Doubly Linked List

时间:2018-07-26 14:53:07      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:tco   ref   nod   layer   level   problems   解法   turn   att   

题目链接:LeetCode 430. Faltten a Multilevel Doubly Linked List

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_iteration(Node *head) {
        if (head == NULL) {
            return NULL;
        }
        for (Node *p = head; p != NULL; p = p->next) {
            Node *next = p->next;
            if (p->child != NULL) {
                p->next = p->child;
                p->child->prev = p;
                p->child = NULL;
                Node *tmp = p->next;
                while (tmp->next != NULL) {
                    tmp = tmp->next;
                }
                tmp->next = next;
                next->prev = tmp;
            }
        }
        return head;
    }
    
    // 解法二:递归
    Node* flatten_recursion(Node *head) {
        if (head == NULL) {
            return head;
        }
        Node *p = head;
        while (p != NULL) {
            if (p->child != NULL) {
                Node *next = p->next;
                Node *nextLayer = flatten_recursion(p->child);
                p->next = nextLayer;
                nextLayer->prev = p;
                p->child = NULL;
                while (nextLayer->next != NULL) {
                    nextLayer = nextLayer->next;
                }
                nextLayer->next = next;
                if (next != NULL) {
                    next->prev = nextLayer;
                }
            }
            p = p->next;
        }
        return head;
    }
};

LeetCode 430. Faltten a Multilevel Doubly Linked List

标签:tco   ref   nod   layer   level   problems   解法   turn   att   

原文地址:https://www.cnblogs.com/xjshi/p/9371018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!