zoukankan      html  css  js  c++  java
  • 复杂链表的复制

    题目描述

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
     
    这个题有两种解法,第一种是用hashmap把原表random(随机指针)对应存起来,再复原,可是这个空间复杂度太高
    第二种方法,把原链表的a-b-c-d变成 a-a1-b-b1-c-c1-d-d1这样,a1的random指针应该指向a指针指向的位置的下一个位置(很好理解)
     
    注意:一定要先将a-b-c-d变成 a-a1-b-b1-c-c1-d-d1,再进行随机指针的变更,(把所有的next指针调好了,再调random指针)
    /*
    public class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;
    
        RandomListNode(int label) {
            this.label = label;
        }
    }
    */
    public class Solution {
        public RandomListNode Clone(RandomListNode pHead)
        {
            RandomListNode Head=pHead;
            if(pHead==null){
                return null;
            }
            RandomListNode cur=pHead;
            RandomListNode next=pHead;
            while(cur!=null){
                next=cur.next;
                cur.next=new RandomListNode(cur.label);
                cur.next.next=next;
                cur=next;
            }
            
            cur=pHead;
            next=pHead;
            while(cur!=null){
                cur.next.random=cur.random==null?null:cur.random.next;
                cur=cur.next.next;;
            }
            RandomListNode pHead1=Head.next;
            while(Head!=null){
                next=Head.next.next;
                Head.next.next=next==null?null:next.next;
                Head.next=next;
                Head=next;
            }
            return pHead1;
    
        }
    }
  • 相关阅读:
    多层级makefile
    vscode常用快捷键
    unix socket接口
    以太网复习
    shell脚本算术运算
    1185: 零起点学算法92——单词数(C)
    1183: 零起点学算法90——海选女主角(C语言)
    1181: 零起点学算法88——偶数求和(C语言)
    1144: 零起点学算法51——数组中删数(C语言)
    列主元消去法&全主元消去法——Java实现
  • 原文地址:https://www.cnblogs.com/tobemaster/p/5903669.html
Copyright © 2011-2022 走看看