LeetCode—copy-list-with-random-pointer—java

题目描述

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.

题意:深拷贝一个链表,链表除了含有next指针外,还包含一个random指针,该指针指向字符串中的某个节点或者为空。

思路解析

  • 先将节点复制,新节点在原节点的后边
  • 然后给新的random赋值
  • 最后把新节点从原链表中拆分出来

代码

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head ==null)
            return head;
        RandomListNode node = head;
        while(node!=null){
            RandomListNode newNode = new RandomListNode(node.label);
            newNode.next = node.next;
            node.next = newNode;
            node=newNode.next;
        }
        node=head;
        while(node!=null){
            if(node.random!=null){
                node.next.random = node.random.next;
            }
            node=node.next.next;
        }
        RandomListNode newHead = head.next;
        node = head;
        while(node!=null){
            RandomListNode newNode = node.next;
            node.next = newNode.next;
            if(newNode.next!=null){
                newNode.next=newNode.next.next;
            }
            node = node.next;
        }
        return newHead;
    }
}

参考:https://blog.csdn.net/ljiabin/article/details/39054999

猜你喜欢

转载自blog.csdn.net/Lynn_Baby/article/details/80565757