扁平化多级双向链表

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

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

 

示例:

输入:
 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
 

以上示例的说明:

给出以下多级双向链表:

我们应该返回如下所示的扁平双向链表:

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

 

思路:

把 多级双向链表左旋45度就可以看作一颗二叉树,我们只需要前序遍历他就可以得到正确的序列,使用这个序列就可以构造出双向链表

 

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

    Node() {}

    Node(int _val, Node* _prev, Node* _next, Node* _child) {
        val = _val;
        prev = _prev;
        next = _next;
        child = _child;
    }
};
*/
class Solution {
public:
    Node* ret;
    Node* tail;
    Node* flatten(Node* head) 
    {
        ret = NULL;
        tail = NULL;
        bianli(head);
        return ret;
    }
    
    void bianli(Node* head)
    {
        if(head != NULL)
        {
            //cout<<head->val<<endl;
            Node* tmp = new Node(head->val,NULL,NULL,NULL);
            if(ret == NULL)
            {
                ret = tmp;
                tail = tmp;
            }
            else
            {
                tail->next = tmp;
                tmp->prev = tail;
                tail = tmp;
            }
            bianli(head->child);
            bianli(head->next);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值