《程序员代码面试指南》第二章 链表问题 复制含有随机指针节点的链表

复制含随机指针链表
本文介绍了一种复制含有随机指针节点的链表的方法。通过先复制节点再复制随机指针,最后拆分链表的方式实现了完整复制。文中还提供了一个Java实现示例,用于验证算法的有效性。
题目
复制含有随机指针节点的链表
java代码
/**
 * @Description:复制含有随机指针节点的链表
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 22:33
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter2_9 {
    public NewNode copyNode(NewNode head) {
        if (head == null) {
            return null;
        }
        //复制一份节点
        NewNode cur = head;
        NewNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = new NewNode(cur.value);
            cur.next.next = next;
            cur = next;
        }
        //复制一份随机数节点
        cur = head;
        while (cur != null) {
            next = cur.next;
            next.rand = cur.rand == null ? null : cur.rand.next;
            cur = next.next;
        }
        //拆分
        cur = head;
        NewNode newNodeHead = head.next;
        NewNode tail = head.next;
        while (cur != null) {
            next = cur.next.next;
            tail.next = next == null ? null : next.next;
            tail = next == null ? null : next.next;
            cur.next = next;
            cur = next;
        }
        return newNodeHead;
    }

    //测试
    public static void main(String[] args) {
        Chapter2_9 chapter = new Chapter2_9();
        NewNode node4 = new NewNode(4, null, null);
        NewNode node3 = new NewNode(3, node4, node4);
        NewNode node2 = new NewNode(2, node3, node3);
        NewNode node1 = new NewNode(1, node2, node4);

        NewNode cur = node1;
        while (cur != null) {
            System.out.print(cur.value + "--");
            if (cur.rand != null) {
                System.out.print(cur.rand.value + "  ");
            }
            cur = cur.next;
        }
        NewNode head = chapter.copyNode(node1);
        System.out.println();
        while (head != null) {
            System.out.print(head.value + "--");
            if (head.rand != null) {
                System.out.print(head.rand.value + "  ");
            }
            head = head.next;

        }
    }
}

class NewNode {
    public int value;
    public NewNode next;
    public NewNode rand;

    public NewNode(int value, NewNode next, NewNode rand) {
        this.value = value;
        this.next = next;
        this.rand = rand;

    }

    public NewNode(int value) {
        this.value = value;
    }
}

转载于:https://www.cnblogs.com/lizhouwei/p/8729400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值