博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指 Offer 35. 复杂链表的复制
阅读量:4036 次
发布时间:2019-05-24

本文共 1871 字,大约阅读时间需要 6 分钟。

题目描述

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

java

大问题拆成三个小问题逐个击破

/*// Definition for a Node.class Node {    int val;    Node next;    Node random;    public Node(int val) {        this.val = val;        this.next = null;        this.random = null;    }}*/class Solution {
public Node copyRandomList(Node head) {
copyNodes(head); copyRandomNodes(head); return reconnectNodes(head); } //第1步:复制所有基础节点,每个节点复制在原节点的后边 public void copyNodes(Node head){
Node cur=head; //创建新节点 while(cur!=null){
Node copy=new Node(cur.val); copy.next=cur.next; cur.next=copy; cur=copy.next; } } //第2步: 将每个节点的随机指针也复制,
,则
public void copyRandomNodes(Node head){
Node cur=head; while(cur!=null){
Node copy_node=cur.next; //复制的节点 if(cur.random!=null){
//这个if语句要注意 copy_node.random=cur.random.next; //复制节点的random节点是原节点的random节点的netx节点 } cur=copy_node.next; } } //第3步,拆成两个链表。 奇数节点属于原始链表;偶数节点属于复制链表 public Node reconnectNodes(Node head){
Node cur=head; Node copy_head=null; Node copy_node=null; if(cur!=null){
copy_head=cur.next; copy_node=cur.next; cur.next=copy_head.next; cur=cur.next; } while(cur!=null){
copy_node.next=cur.next; copy_node=copy_node.next; cur.next=copy_node.next; cur=cur.next; } return copy_head; }}
你可能感兴趣的文章
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Word Break(python)
查看>>
【剑指offer】面试题26:复杂链表的复制
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java swing最简单实例(2) 往JFrame里面放一个容器或组件
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
AngularJS2中最基本的文件说明
查看>>
从头开始学习jsp(2)——jsp的基本语法
查看>>
从头开始学习JSP(3)——一些配置
查看>>
html常用标签快速检索
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>
DIV/CSS:一个贴在左上角的标签
查看>>
通过/proc/PID/status查看进程内存占用情况
查看>>