链表
复制带随机指针的链表
方法一
借助Map
public Node copyRandomList(Node head, int type) {
HashMap<Node, Node> map = new HashMap<>(10);
Node cur = head;
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while (cur != null) {
Node copyNode = map.get(cur);
copyNode.random = map.get(cur.random);
cur = cur.next;
}
cur = head;
while (cur != null) {
Node next = cur.next;
map.get(cur).next = map.get(next);
cur = cur.next;
}
return map.get(head);
}
方法二
需要遍历链表3此
package com.vitamin.list;
import org.junit.Test;
/**
* 复制带随机指针的链表
*
* @author vitamin
* 2022/4/3 21:25
*/
public class CopyRandomList {
@Test
public void test() {
Node node0 = new Node(7);
Node node1 = new Node(13);
Node node2 = new Node(11);
Node node3 = new Node(10);
Node node4 = new Node(1);
node0.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node1.random = node0;
node2.random = node4;
node3.random = node2;
node4.random = node0;
Node node = copyRandomList(node0);
while (node != null) {
System.out.println(node.val);
System.out.println(node.random);
node = node.next;
}
}
/**
* 复制链表
* 遍历3遍
*
* @param head
* @return
*/
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Node currentNode = head;
while (currentNode != null) {
Node nodeCopy = new Node(currentNode.val * 10);
Node next = currentNode.next;
nodeCopy.next = next;
currentNode.next = nodeCopy;
currentNode = next;
}
currentNode = head;
while (currentNode != null) {
// 老链表的random
Node random = currentNode.random;
// 复制出来的节点
Node newNode = currentNode.next;
// 更改random 指针的方向
newNode.random = random == null ? null : random.next;
//指针后移
currentNode = currentNode.next.next;
}
currentNode = head;
Node newHead = head.next;
while (currentNode != null) {
// 新的节点
Node newNode = currentNode.next;
// 源节点的next指向
currentNode.next = newNode.next;
// 新节点的next指向
newNode.next = currentNode.next == null ? null : currentNode.next.next;
currentNode = currentNode.next;
}
return newHead;
}
}
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
@Override
public String toString() {
return String.valueOf(this.val);
}
}