Saturday, February 26, 2022

LeetCode 430. Flatten a Multilevel Doubly Linked List

https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
/*
// 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 head;
auto p = head;
while(p){
auto cur = p;
if(cur->child){
auto next = cur->next;
// set child to next
cur->next = cur->child;
cur->next->prev = cur;
// set child to null
cur->child = NULL;
// set next to child's tail
while(cur->next)
cur = cur->next;
if(next) next->prev = cur;
cur->next = next;
}
p = p->next;
}
return head;
}
};

No comments:

Post a Comment