递归求解,将一个链表放平
ref{:target=”_blank”}
C++ 代码
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
Node* flatten(Node* head) {
return dfs(head).first;
}
// 返回 head 和 tail 节点
pair<Node*, Node*> dfs(Node* head) {
if(!head)return {nullptr, nullptr};
Node* tail = head;
for(auto cur = head; cur != nullptr;) {
tail = cur;
if(cur->child) {
auto next = cur->next;
auto res = dfs(cur->child);
auto child_head = res.first, child_tail = res.second;
// child节点置0
cur->child = nullptr;
// 重新连接头尾节点
cur->next = child_head;
child_head->prev = cur;
child_tail->next = next;
if(next)next->prev = child_tail;
// 更新cur 和 tail
cur = next;
tail = child_tail;
} else {
cur = cur->next;
}
}
return {head, tail};
}
};
这dev编译不过去!!!!!!!!
leetcode可以ac 报什么错误呢
19 5 C:\Users\lenovo\Desktop\11111.cpp [Error] ‘pair’ does not name a type
这个是c++代码吗?
c++ 代码,是不是没有包含头文件