关闭

138. Copy List with Random Pointer

标签: listleetcodeclone
70人阅读 评论(0) 收藏 举报
分类:

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.

code

注意某个节点没有next,但是有random的情况

/**
 * Definition for singly-linked list with a random pointer.
 * public class RandomListNode {
 *     public int label;
 *     public RandomListNode next, random;
 *     public RandomListNode(int x) { this.label = x; }
 * };
 */

public class Solution {
    public RandomListNode CopyRandomList(RandomListNode head) {
        if(head==null) return head;
        RandomListNode clonehead = new RandomListNode(head.label);
        if(head.next!=null)
            clonehead.next = new RandomListNode(head.next.label);
        if(head.random!=null)
            clonehead.random = new RandomListNode(head.random.label);       
        RandomListNode next = CopyRandomList(head.next);
        var cur = clonehead.next;
        if(next!=null){
            cur.next = next.next;
            cur.random = next.random;
        }    
        return clonehead;
    }
}
2
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    Leetcode Solutions in Github

    Click me

    Leetcode solutions in Github, including tags: Array, HashTable, Stack, Queue, LinkedList, Tree, Graph,...

    leetcode-manager

    Click me

    Current Leetcode manager: it's used by Entity Framework, WinForms, Sql Server to manage leetcode questions that we have done. Functions include tags creation, revise and deletion, and questions creation, edit and deletion.

    个人资料
    • 访问:96455次
    • 积分:4542
    • 等级:
    • 排名:第6435名
    • 原创:292篇
    • 转载:0篇
    • 译文:0篇
    • 评论:54条
    博客专栏