leetcode_138 Copy List with Random Pointer

来源:互联网 发布:中国网络移动经纪人 编辑:程序博客网 时间:2024/06/01 18:08
  • 题目分析:

    给定一个特殊的单链表,链表的每一个节点多了一个随机指针域,随机指向链表中的某一个节点。要求复制这个链表

  • 解题思路:

    1)复制节点,并将拷贝后的节点插入到原节点的后面;

    2)更新所有复制的节点的random节点,即:h.next.random = h.random.next;

    3)将原链表与复制的链表断开。

    补充:也可以利用map来保存random节点之间的关系,通过递归或非递归来实现。

  • 实现程序

    • C++版本

      class Solution{    public:        RandomListNode *copyRandomList(RandomListNode *head)        {            if (head == NULL)                return NULL;            // 步骤1:复制节点,并将复制后的节点插入到原节点的后面             RandomListNode *pos1 = head, *pos2 = head->next;             while (pos1 != NULL)            {                pos1->next = new RandomListNode(pos1->label);                pos1->next->next = pos2;                pos1 = pos2;                if (pos2 != NULL)                    pos2 = pos2->next;            }            // 步骤2:更新所有复制的节点的random节点,即h.next.random = h.random.next             pos1 = head;             pos2 = head->next;            while (pos1 != NULL)            {                if (pos1->random == NULL)                    pos2->random = NULL;                else                    pos2->random = pos1->random->next;                pos1 = pos1->next->next;                if (pos2->next != NULL)                    pos2 = pos2->next->next;            }             // 步骤3:将原链表与复制的链表断开             RandomListNode *res = head->next;            pos1 = head;            pos2 = head->next;            while (pos1->next != NULL)            {                pos1->next = pos2->next;                pos1 = pos2;                if (pos2->next != NULL)                    pos2 = pos2->next;            }            pos1->next = NULL;            pos2->next = NULL;            return res;        }}   
    • Java版本

      public RandomListNode copyRandomList2(RandomListNode head) {    if (head == null)        return null;    // 遍历链表,复制节点,并将复制的节点放到原节点的后面    RandomListNode h = head;    while (h != null) {        RandomListNode copy = new RandomListNode(h.label);        RandomListNode next = h.next;        h.next = copy;        copy.next = next;        h = next;    }    // 遍历链表,更改链表的random节点    h = head;    while (h != null) {        if (h.random != null) {            h.next.random = h.random.next;        }        h = h.next.next;    }    // 遍历节点,将原链表与复制链表断开    h = head;    RandomListNode newHead = h.next;    while (h != null) {        RandomListNode copy = h.next;        h.next = copy.next;        h = h.next;        copy.next = h != null ? h.next : null;    }    return newHead;}
0 0