链表:深度拷贝带随机指针的链表代码1
使用HasnMap的方式
深度拷贝带随机指针的链表:
时间复杂度:O(n),虽然有两个循环,但是没有嵌套,因此是O(2n) => O(n)
空间复杂度:O(n),因为用到了hashmap来存储random指针,深拷贝,因此拷贝所占用的空间不计
import java.util.HashMap;
import java.util.Map;
public class Test1 {
public static class ListNode {
Object value;
ListNode next;
ListNode random;
public ListNode(Object value, ListNode next, ListNode random) {
this.value = value;
this.next = next;
this.random = random;
}
public ListNode(Object value) {
this.value = value;
}
@Override
public String toString() {
return "ListNode{" +
"value=" + value +
", next=" + next +
", random=" + random +
'}';
}
public void setRandom(ListNode random) {
this.random = random;
}
}
/**
* 深度拷贝带随机指针的链表
* 时间复杂度:O(n),虽然有两个循环,但是没有嵌套,因此是2O(n) => O(n)
* 空间复杂度:O(n),因为用到了hashmap来存储random指针
*
* @param head
* @return
*/
public static ListNode copyRandomList(ListNode head) {
if (head == null) {//规范的代码都会做防空判断
return head;
}
Map<ListNode, ListNode> map = new HashMap<>();
ListNode newHead = head;
while (null != newHead) {
if (!map.containsKey(newHead)) {
ListNode copyNode = new ListNode(newHead.value);
map.put(newHead, copyNode);
}
if (null != newHead.random) {
ListNode randomNode = newHead.random;
if (!map.containsKey(randomNode)) {
ListNode copyRandom = new ListNode(randomNode.value);
map.put(randomNode, copyRandom);
}
map.get(newHead).random = map.get(randomNode);
}
newHead = newHead.next;
}
newHead = head;
while (null != newHead) {
ListNode next = newHead.next;
map.get(newHead).next = map.get(next);
newHead = newHead.next;
}
return map.get(head);
}
public static void main(String[] args) {
ListNode node6 = new ListNode(66, null, null);
ListNode node5 = new ListNode(55, node6, null);
ListNode node4 = new ListNode(44, node5, null);
ListNode node3 = new ListNode(33, node4, node5);
ListNode node2 = new ListNode(22, node3, null);
ListNode node1 = new ListNode(11, node2, node6);
// node6.setRandom(node1);//toString会死循环,因此不加,已经可以完成深度拷贝
System.out.println(node1);//ListNode{value=11, next=ListNode{value=22, next=ListNode{value=33, next=ListNode{value=44, next=ListNode{value=55, next=ListNode{value=66, next=null, random=null}, random=null}, random=null}, random=ListNode{value=55, next=ListNode{value=66, next=null, random=null}, random=null}}, random=null}, random=ListNode{value=66, next=null, random=null}}
ListNode copyRandomList = copyRandomList(node1);
System.out.println(copyRandomList);//ListNode{value=11, next=ListNode{value=22, next=ListNode{value=33, next=ListNode{value=44, next=ListNode{value=55, next=ListNode{value=66, next=null, random=null}, random=null}, random=null}, random=ListNode{value=55, next=ListNode{value=66, next=null, random=null}, random=null}}, random=null}, random=ListNode{value=66, next=null, random=null}}
}
}