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

48 篇文章 0 订阅
46 篇文章 0 订阅

【题目】
有一种特殊的链表节点类,如下所示

class Node{
     int value;
     Node next;
     Node rand;
     Node(int val){
         value = val;
     }
}

rand指针是单链表节点结构中新增的指针,rand可能指向链表中的任意一个结点,或者是null,
给定一个由Node节点类型组成的无环单链表的头节点head,
请实现一个函数,完成这个链表的复制,并返回复制的新链表的头节点
【要求】时间复杂度是O(N),额外空间复杂度是O(1)
【思路】
有2种方式:

  1. 利用hashmap,用原链表节点作key,value为新建节点,复制相应的next节点和rand节点
  2. 在原链表的基础上复制链表,最后分离开来
    具体代码实现如下

hashmap

private static Node copyListWithRandom1(Node head){
	HashMap<Node, Node> map = new HashMap<>();
    Node cur = head;
    while (null != cur){
        map.put(cur,new Node(cur.value));
        cur = cur.next;
    }
    cur = head;
    while (null != cur){
        map.get(cur).next = map.get(cur.next);
        map.get(cur).rand = map.get(cur.rand);
        cur = cur.next;
    }
    return map.get(head);
}

复制链表

private static Node copyListWithRandom2(Node head){
	Node cur = head;
    Node next;

    //复制节点
    while (null != cur){
        next = cur.next;
        cur.next = new Node(cur.value);
        cur.next.next = next;
        cur = next;
    }

    cur = head;
    while (null != cur){
        if (null != cur.rand){
            cur.next.rand = cur.rand.next;
        }
        cur = cur.next.next;
    }
    cur = head;
    Node res = head.next;
    Node copyNode;
    //分离
    while (null != cur){
        next = cur.next.next;
        copyNode = cur.next;
        cur.next = next;
        copyNode.next = null != next ? next.next : null;
        cur = next;
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值