Copy List with Random Pointer

来源:互联网 发布:苹果电脑流程图软件 编辑:程序博客网 时间:2024/05/16 18:49

题: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.

题意:copy一个链表(深拷贝),链表包含一个next指针和一个random指针,其中random指针指向字符串中的某个节点或者为空。

分析:

 第一步: 在原链表的每个节点后面,复制一个新的节点(就是把每个节点复制两份),原链表长度变为 2 倍,random 指针指向的是 原链表节点 random 指针指向的节点的后面的那个节点

第二步: 将链表拆成两个 lists

实现

     节点结构:

          class RandomNode {
                 int sign;
                 RandomNode next, random;
                 RandomNode(int x) { this.sign= x; }    

               } 

   算法代码:

public class leetcode {class RandomNode {    int sign;    RandomNode next, random;    RandomNode(int x) { this.sign = x; }};    public RandomNode copyList(RandomNode head) {        if (head == null) return null;                RandomNode oldnode = head;        while (oldnode != null) {        RandomNode newnode = new RandomNode(oldnode.sign);            newnode.next = oldnode.next;            oldnode.next = newnode;            oldnode = newnode.next;        }                oldnode = head;        while (oldnode != null) {            if (oldnode.random != null) oldnode.next.random = oldnode.random.next;            oldnode = oldnode.next.next;        }                RandomNode newhead = head.next;        oldnode = head;        while (oldnode != null) {        RandomNode newnode = oldnode.next;        oldnode.next = newnode.next;            if (newnode.next != null) newnode.next = newnode.next.next;            oldnode = oldnode.next;        }                return newhead;    }}


0 0