leetcode题解-138. Copy List with Random Pointer

题目: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. 调整这些复制节点的Random域的值了,使其指向与原链表对应节点的复制节点;

  3. 调整所有复制节点的Next域的值,并恢复原始链表所有节点的Next的值到初始状态!

这样就很清晰了,代码分三次循环分别完成上述三个目标即可,这种方法击败了70%多的用户。代码入下:

    public static RandomListNode copyRandomList1(RandomListNode head) {
        RandomListNode iter = head, next;

        // First round: make copy of each node,
        // and link them together side-by-side in a single list.
        while (iter != null) {
            next = iter.next;

            RandomListNode copy = new RandomListNode(iter.label);
            iter.next = copy;
            copy.next = next;

            iter = next;
        }

        // Second round: assign random pointers for the copy nodes.
        iter = head;
        while (iter != null) {
            if (iter.random != null) {
                iter.next.random = iter.random.next;
            }
            iter = iter.next.next;
        }

        // Third round: restore the original list, and extract the copy list.
        iter = head;
        RandomListNode pseudoHead = new RandomListNode(0);
        RandomListNode copy, copyIter = pseudoHead;

        while (iter != null) {
            next = iter.next.next;

            // extract the copy
            copy = iter.next;
            copyIter.next = copy;
            copyIter = copy;

            // restore the original list
            iter.next = next;

            iter = next;
        }

        return pseudoHead.next;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值