LeetCode – Flatten a Multilevel Doubly Linked List

题目:

You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

Example:

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

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

解题:

1. 先判断child节点是否为空,如果是存在;否则继续遍历;
2. 如果存在child,将当前节点的next节点保存, 将当前节点的next指向child节点, 设置child的prev为当前节点,清空child节点;
2. 找到child链表的末尾节点;
3. child末尾节点指向保存的next节点, next节点指向child节点的末尾节点。
 

实现:

/*
// 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* flatten(Node* head) {
        Node *cur = head;
        while (cur!=NULL){
            if (cur->child!=NULL){
                Node* next = cur->next;
                cur->next = cur->child;
                cur->child->prev = cur;
                cur->child = NULL;
                Node *p = cur->next;
                while(p->next!=NULL&&p!=NULL) {
                    p= p->next;
                }
                p->next = next;
                if (next!=NULL){
                    next->prev = p;
                }
            }
            cur= cur->next;
        }
        return head;
        
    }
};
// 时间复杂度O(N) ,空间复杂度O(1)

Be First to Comment

发表回复