刷题No28. copy-list-with-random-pointer(深拷贝一个链表)(java)【链表】

题目:

现在有一个这样的链表:链表的每一个节点都附加了一个随机指针,随机指针可能指向链表中的任意一个节点或者指向空。

请对这个链表进行深拷贝。

思路:

  • 先将原节点进行复制
  • 再将原节点的random指针进行复制
  • 从链表中将复制的节点拆分出来

代码:

package com.company;

public class TestNo28 {
    static class RandomListNode{
        int val;
        RandomListNode next,random;
        RandomListNode(int x){
            this.val = x;
        }
        public String toString(){
            if(this.next == null){
                return String.valueOf(this.val);
            }
            return this.val + "->" + this.next.toString();
        }
    }
    public static void main(String[] args) {
        TestNo28 t = new TestNo28();
        RandomListNode head = new RandomListNode(0);
        head.next = new RandomListNode(2);
        head.next.next = new RandomListNode(5);
        head.next.next.next = new RandomListNode(7);
        System.out.println(head);
        System.out.println(t.copyRandomList(head));
    }
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null){
         return head;
        }
        //对原节点进行复制
        RandomListNode node = head;
        while (node!= null){
            RandomListNode newNode = new RandomListNode(node.val);
            newNode.next =node.next;
            node.next = newNode;
            node = newNode.next;
        }
        
        //对原节点的Random指针进行复制
        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;
    }
}

 

发布了64 篇原创文章 · 获赞 13 · 访问量 4394
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章