[程序员代码面试指南]链表问题-复制含有随机指针节点的链表(方法二待做)

问题描述

public class Node {
	public int val;
	public Node next;
	public Node rand;
	
	public Node(int data) {
		this.val=data;
	}
}
Node类中的value是节点值,next指针和正常单链表中next指针的意义一样,都指向下一个节点,rand指针是Node类中新增的指针,这个指针可能指向链表中的任意一个节点,也可能指向null。 
给定一个由Node节点类型组成的无环单链表的头节点head,请实现一个函数完成这个链表中所有结构的复制,并返回复制的新链表的头节点。
进阶:不使用额外的数据结构,只用有限几个变量,且在时间复杂度为O(N)内完成原问题要实现的函数。

题解

方法一:
使用哈希表。
时间复杂度O(n),额外空间复杂度O(n)
方法二:
todo

代码(方法一)

import java.util.HashMap;

public class Main {
	public static void main(String args[]) {
		Node n1=new Node(1);
		Node n2=new Node(2);
		Node n3=new Node(3);
		Node n4=new Node(4);
		Node n5=new Node(5);
		n1.next=n2;
		n2.next=n3;n2.rand=n1;
		n3.next=n4;
		n4.next=n5;n4.rand=n5;
		
		Node head=n1;
		Node newHead=copyRandList(head);
		Node p=newHead;
		while(p.next!=null) {
			System.out.println(p.val);
			System.out.println(p.rand);
			p=p.next;
		}
	}
	
	public static Node copyRandList(Node head){
        
        HashMap<Node, Node> map=new HashMap<Node, Node>();
        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).rand=map.get(cur.rand);
            cur=cur.next;
        }
        return map.get(head);
    }
}

posted on   coding_gaga  阅读(109)  评论(0编辑  收藏  举报

编辑推荐:
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示