[各种面试题] 复制带随机节点的链表

来源:互联网 发布:淘宝孕妇装 编辑:程序博客网 时间:2024/04/29 09:27

给定一个单链表,链表除了包含next指针外,还包含一个random指针,该指针指向链表中某个结点。

请复制链表到一个新的链表,random指针需要指向新链表中对应的结点。比如原链表某个结点random指针指向第2个结点,那么新结点的random指针也要指向到新链表的第2个结点。

提示:此题存在空间复杂度O(1)的算法,不需要使用任何额外辅助空间。请不要改变原链表的结构。

哎,写代码差死了,根本没希望一次写对。各种遗漏各种笔误各种没想清楚。

/**链表结点的定义(请不要在代码中定义该类型)struct ListNode {    ListNode *next;    ListNode *random;};*/// 返回复制的新链表头结点ListNode* copyListWithRandomPtr(ListNode *head) {if ( !head ) return head;ListNode* pcur=head;while(pcur){ListNode* newAdd= new ListNode;newAdd->next=pcur->next;pcur->next=newAdd;pcur=newAdd->next;}ListNode* pre=head;while(pre){pcur=pre->next;pcur->random=pre->random->next;pre=pcur->next;}ListNode guard;ListNode* tail=&guard;pre=head;while(pre){tail->next=pre->next;tail=tail->next;pre->next=pre->next->next;pre=pre->next;}return guard.next;}




原创粉丝点击