随机链表的复制

这篇博客探讨了如何使用两种方法在Java中复制一个带有随机指针的链表。第一种方法利用HashMap将原链表的节点映射到新节点,然后更新新节点的next和random指针。第二种方法则是复制节点并插入原链表,之后重新连接random指针并拆分链表。这两种方法都有效地实现了链表的深拷贝。
摘要由CSDN通过智能技术生成

在这里插入图片描述

import java.util.HashMap;
public class Main {
	public static void main(String[] args) {
		// Scanner sc = new Scanner(System.in);
		Node p1 = new Node(null, 1, null);
		Node p2 = new Node(null, 2, null);
		Node p3 = new Node(null, 3, null);
		Node p4 = new Node(null, 4, null);
		p1.next = p2;
		p2.next = p3;
		p3.next = p4;
		p1.random = p3;
		p2.random = p4;
		Node res1 = copy1(p1);
		Node res2 = copy2(p1);
	}

	public static Node copy1(Node head) {
		HashMap<Node, Node> map = new HashMap<>();
		Node cur = head;
		while (cur != null) {
			map.put(cur, new Node(cur.val));
			cur = cur.next;
		}
		cur = head;
		while (cur != null) {
			map.get(cur).next = map.get(cur.next);
			map.get(cur).random = map.get(cur.random);
			cur = cur.next;
		}
		return map.get(head);
	}

	public static Node copy2(Node head) {
		if (head == null)
			return null;
		Node p = head;
		// copy every node and insert to list
		while (p != null) {
			Node copy = new Node(p.val);
			copy.next = p.next;
			p.next = copy;
			p = copy.next;
		}
		// copy random pointer for each new Node
		p = head;
		while (p != null) {
			if (p.random != null) {
				p.next.random = p.random.next;
			}
			p = p.next.next;
		}
		// break list to two
		p = head;
		Node newHead = head.next;
		while (p != null) {
			Node tmp = p.next;
			p.next = tmp.next;
			if (tmp.next != null) {
				tmp.next = tmp.next.next;
			}
			p = p.next;
		}
		return newHead;
	}
}

class Node {
	Node next;
	Node random;
	int val;

	public Node(int val) {
		super();
		this.val = val;
	}

	public Node(Node next, int val, Node random) {
		this.next = next;
		this.val = val;
		this.random = random;
	}
}

懵懵懂懂,知道个大概,先记录一下,今后有空再来深入学习,本文参考:
某大佬代码

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值