Copy of Leetcode List with Random Pointer (23)

Source: Internet
Author: User

A deep copy of a linked list, the difference is that the list has an extra random pointer. Reference: http://blog.csdn.net/ljiabin/article/details/39054999

The procedure is very ingenious, divided into three steps, one is the new node, and placed after the old node, the second is to modify the new node of the random pointer, and the third is to break the old and new list.

Randomlistnode *randomlist (Randomlistnode *head) {          //Copy each node and place the new node after the old node           for(Randomlistnode *cur = head; Cur! =nullptr;) {Randomlistnode*node =NewRandomlistnode (cur->label); Node->next = cur->Next; Cur->next =node; Cur= node->Next; }          //to modify the random pointer of a new node           for(Randomlistnode *cur = head; Cur! =nullptr;) {              if(Cur->random! = nullptr) Cur->next->random = cur->random->Next; Cur= cur->next->Next; }          //break the old and new linked listRandomlistnode Dummy (-1);  for(Randomlistnode *cur = head,*new_cur=&dummy; cur! =nullptr;) {New_cur->next = cur->Next; New_cur= new_cur->Next; Cur->next = cur->next->Next; Cur= cur->Next; }          returnDummy.next; }
View Code

Copy of Leetcode List with Random Pointer (23)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.