整理双链表

给定双链表,带数据项,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;		
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值