• copy a random link


    题目:
    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
    Return a deep copy of the list.
     
     1 /**
     2 * Definition for singly-linked list with a random pointer.
     3 * struct RandomListNode {
     4 *     int label;
     5 *     RandomListNode *next, *random;
     6 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     7 * };
     8 */
     9 class Solution {
    10 public:
    11     RandomListNode *copyRandomList(RandomListNode *head) {
    12         if(head == NULL) return NULL;
    13         //将新节点复制到原来节点后面
    14         RandomListNode *copy;
    15         RandomListNode *p = head;
    16         RandomListNode *tmp;
    17         while(p!=NULL)
    18         {
    19             copy = new RandomListNode(p->label);
    20             tmp = p->next;
    21             p->next = copy;
    22             copy->next = tmp;
    23             p = tmp;
    24         }
    25         //将新结点与随机结点相连接     
    26         p = head;
    27         copy = head->next;
    28         while(p!=NULL && copy!=NULL)
    29         {
    30             copy->random = ((p->random)?p->random->next:NULL);
    31             p = ((copy->next)?copy->next:NULL);
    32             copy = ((p->next)?p->next:NULL);
    33         }
    34         //将新节点与原结点拆开
    35         p = head;
    36         head = copy = head->next;
    37         while(p!=NULL && copy!=NULL)
    38         {
    39             p->next = ((copy->next)?copy->next:NULL);
    40             p = ((p->next)?p->next:NULL);
    41             copy->next = ((p)?p->next:NULL);
    42             copy = ((copy->next)?copy->next:NULL);
    43         }
    44         return head;
    45     }
    46 };
  • 相关阅读:
    [C#]获取指定文件文件名、后缀、所在目录等
    Mysql 存储引擎中InnoDB与Myisam的主要区别
    MySQL的btree索引和hash索引的区别
    Mysql事务的隔离级别
    AE序列号
    mysql索引类型说明
    去除url中自带的jsessionid
    redirect传值非url(springmvc3)
    ueditor的使用
    mysql用户管理(开户、权限)
  • 原文地址:https://www.cnblogs.com/dzy521/p/9144690.html
Copyright © 2020-2023  润新知