链表的深拷贝(复杂链表的复制)

Main.java:

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();//创建一个solution对象
        testComplexListCopy(solution);   //复杂链表的复制
        //testReverseList();//反转链表
        //testRemoveAll();//移除链表中给定的值
    }
    private static void testComplexListCopy(Solution solution) {//复杂链表的复制,这只是测试,并不是具体的方法,所以不用要返回值
        // 1. 构建测试数据
        CNode head = createComplexList1();
        // 2. 进行测试
        CNode resultHead = solution.copy(head);
        // 3. 对测试结果进行打印
        printCList(resultHead);
    }
    // CNode 必须有一个构造方法,形参是 int val
    // 并且,初始化后,next 和 random 都是 null
    private static CNode createComplexList1() { //创建复杂链表
        CNode n1 = new CNode(1);
        CNode n2 = new CNode(2);
        CNode n3 = new CNode(3);
        CNode n4 = new CNode(4);

        n1.random = n3; n2.random = n1; n3.random = n3;//手动形成random
        n1.next = n2; n2.next = n3; n3.next = n4;//手动形成链表

        return n1;//返回的是链表
    }

    // CNode 必须实现一个 String toString() 方法
    private static void printCList(CNode head) {
        for (CNode cur = head; cur != null; cur = cur.next) {
            System.out.print(cur + " --> ");
        }
        System.out.println();
    }
}

CNode.java:

public class CNode {
    int val;
    CNode next=null;
    CNode random=null;

    public CNode(int val) {
        this.val = val;
    }//IDEA环境下可Alt+Insert生成
    public String toString() {
        return String.format("CNode(%d)", val);
    }
}
Solution.java:

public class Solution {
    CNode copy(CNode head) {
        if (head == null) {
            return null;
        }

        CNode p1 = head;
        while (p1 != null) {
            CNode p2 = new CNode(p1.val);
            //=CNode p2=new CNode();
            // p2.val=p1.val;
            p2.next = p1.next;
            p1.next = p2;

            p1 = p2.next;
        }//此时p2已经完全插入到p1后面了
        
        //处理random指向
        p1 = head;
        while (p1 != null) {
            CNode p2 = p1.next;
            if (p1.random != null) {
                p2.random = p1.random.next;
            }

            p1 = p2.next;
        }

        //拆分链表
        p1 = head;
        CNode newHead = head.next;
        while (p1 != null) {
            CNode p2 = p1.next;
            p1.next = p2.next;
            if (p2.next != null) {
                p2.next = p2.next.next;
            }

            p1 = p1.next;
        }
        return newHead;
    }
}

在这里插入图片描述

发布了61 篇原创文章 · 获赞 3 · 访问量 1213

猜你喜欢

转载自blog.csdn.net/qq_44847147/article/details/103892318
今日推荐