给定双链表,带数据项,previous,next指针,还有一个可能指向另一个同一类型的双链表的头的指针child。将此树变为一个单链表...使用最小的空间和时间复杂度。双链表的头指针和尾指针已经给出。
Given a doubly linked list with a data item, a previous and a next ptr along with another pointer "child" that may point to the head of another doubly linked list of same type(it will lead to a general tree type of structure) or it may be null. Flatten the tree into a linked list... minimum space and time complexity(order n). The doubly linked lists's head and tail are given.
从head开始,如果child指针存在,做一个指向child的链接,追踪到child链表的最后的节点,将其链接到当前节点的下一个节点。然后移动到下一个节点,直到结尾。
start from head, if child is existed make a link to the child, and trace until the end of child's chain and link to the next node of the current pointer. move to the next node until the end.
struct Node{
int d;
Node* next,*last,* child;
};
Node * FlattenNodes(Node *head){
Node * p = head;
while (p!=NULL)
{
if (p->child != NULL)
{
Node * ch = p->child;
while (ch != NULL)
ch = ch->next;
p->child->last = p;
ch->next = p->next;
if (p->next != NULL)
p->next->last = ch;
p->next = ch->child;
p->child = NULL;
}
p = p->next;
}
return head;
}