Day21: [LeetCode中等] 430. 扁平化多级双向链表
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/
思路:
我用的是递归的思想,这道题很适合递归。
代码:
dirty code凑合看吧
/*
// 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;
}
};
*/
Node *res,*rear;
void f(Node *head){
auto p=head;
while(p){
Node* temp=new Node(p->val,NULL,NULL);
if(rear){
rear->next=temp;
temp->prev=rear;
temp->next=NULL;
rear=rear->next;
}else{
rear=res=temp;
temp->prev=NULL;
temp->next=NULL;
}
if(p->child){
f(p->child);
}
temp->child=NULL;
p=p->next;
}
}
class Solution {
public:
Node* flatten(Node* head) {
if(!head) return head;
res=NULL;
rear=NULL;
f(head);
return res;
}
};