leetcode 之Copy List with Random Pointer(23)

深拷贝一个链表,不同的是这个链表有个额外的随机指针。参考:http://blog.csdn.net/ljiabin/article/details/39054999

做法非常的巧妙,分成三步,一是新建结点,并放在旧结点之后;二是修改新结点的random指针;三是将新旧链表断开。

RandomListNode *randomList(RandomListNode *head)
      {
          //复制每个结点,并将新结点放在旧结点之后
          for (RandomListNode *cur = head; cur != nullptr;)
          {
              RandomListNode *node = new RandomListNode(cur->label);
              node->next = cur->next;
              cur->next = node;
              cur = node->next;
          }

          //修改新结点的Random指针
          for (RandomListNode *cur = head; cur != nullptr;)
          {
              if (cur->random != nullptr)cur->next->random = cur->random->next;

              cur = cur->next->next;
          }

          //将新旧链表断开
          RandomListNode 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;

          }

          return dummy.next;
      }
View Code

 

posted @ 2016-05-21 15:29  牧马人夏峥  阅读(104)  评论(0编辑  收藏  举报