复制双链表 Copy a linked list with next and arbit pointer

来源:互联网 发布:网络黑市怎么打开 编辑:程序博客网 时间:2024/05/21 05:05

复制双链表 Copy a linked list with next and arbit pointer

有一个双链表,这个双链表的一个指针指向下一个节点,另一个指针随机指向链表中的任意一个节点。写个函数,复制这个双链表。

Let us call the second pointer as arbit pointer as it can point to any arbitrary node in the linked list.

ArbitLinked List1

Arbitrary pointers are shown in red and next pointers in black。

1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N afte the Nth node
2) Now copy the arbitrary link in this fashion

     original->next->arbitrary = original->arbitrary->next;  /*TRAVERSE TWO NODES*/

This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.

     original->next = original->next->next;     copy->next = copy->next->next;

4) Make sure that last element of original->next is NULL.

Time Complexity: O(n)
Auxiliary Space: O(1)



0 0
原创粉丝点击