leetcode刷题430. 扁平化多级双向链表

题目描述:您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。

扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

示例 :

输入:
 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL

输出:
1-2-3-7-8-11-12-9-10-4-5-6-NULL

思路:
1、判断是否有当前节点child,若无,则 cur = cur->next;
2、若有,将cur的child作为cur的next与cur双向连接
3、将cur的原next连接到child链的末尾
注意:
1、判断头指针是否为空;
2、要同时判断_tail和_tail->next同时存在,才能_tail = _tail->next;

/*
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 nullptr;
        Node *cur=head;
        while(cur){
            Node* _next = cur->next;
            if(cur->child){
                // 存在child节点,将child作为cur的next与cur双向连接
                Node* _child = cur->child;
                cur->next = _child;
                _child->prev = cur;
                cur->child = nullptr;
                // 获取_child链的尾节点
                Node* _tail = _child;
                while(_tail&&_tail->next){
                    _tail = _tail->next;
                }
                // 将将_next挂到_child的末尾
                _tail->next = _next;
                if(_next){
                    _next->prev = _tail;
                }
            }
            cur = cur->next;
        }
        return head;
    }
};
发布了29 篇原创文章 · 获赞 0 · 访问量 514

猜你喜欢

转载自blog.csdn.net/weixin_43022263/article/details/104263482