[leetcode]138. Copy List with Random Pointer@Java解题报告

https://leetcode.com/problems/copy-list-with-random-pointer/description/


A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.



package go.jacob.day804;

import java.util.HashMap;
import java.util.Map;

/**
 * 138. Copy List with Random Pointer 题意是:返回一个链表的深拷贝
 * 
 * @author Jacob
 *
 */
public class Demo2 {
	/*
	 * 推荐解答:使用map,每一个原链表节点,在map中对应新链表的节点
	 */
	public RandomListNode copyRandomList(RandomListNode head) {
		if (head == null)
			return null;
		Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
		RandomListNode node = head;
		while (node != null) {
			map.put(node, new RandomListNode(node.label));
			node = node.next;
		}

		node = head;
		while (node != null) {
			map.get(node).next = map.get(node.next);
			map.get(node).random = map.get(node.random);
			node = node.next;
		}

		return map.get(head);
	}

	/*
	 * 剑指offer中的解答,会改变原链表的结构。 需要额外操作来恢复原链表的结构
	 * 链表的题目画图比较清晰
	 */
	public RandomListNode copyRandomList_1(RandomListNode head) {
		if (head == null)
			return null;
		RandomListNode node = head;
		// 在原链表每个节点后插入一个复制的节点
		while (node != null) {
			RandomListNode newNode = new RandomListNode(node.label);
			RandomListNode temp = node.next;
			node.next = newNode;
			newNode.next = temp;
			node = temp;
		}
		node = head;
		// 复制随机节点
		while (node != null) {
			RandomListNode tempRandom = node.random;
			if (tempRandom != null) {
				node.next.random = tempRandom.next;
			} else
				node.next.random = null;
			node = node.next.next;
			
		}
		//恢复原链表和生成新链表
		RandomListNode newHead = head.next;
		RandomListNode newNode = head.next;
		node = head;
		while (newNode != null) {
			node.next=newNode.next;
			node = newNode.next;
			if (node != null){
				newNode.next = node.next;
				
			}
			else
				newNode.next = null;
			newNode = newNode.next;
		}

		return newHead;
	}

	private class RandomListNode {
		int label;
		RandomListNode next, random;

		RandomListNode(int x) {
			this.label = x;
		}
	};
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值