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

题目

复制含有随机指针节点的链表

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;
    }
}
posted @ 2018-04-06 23:23  lizhouwei  阅读(113)  评论(0编辑  收藏  举报