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

    题目描述

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

    思路:
    *1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
    *2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
    *3、拆分链表,将链表拆分为原链表和复制后的链表

    /*
    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)
        {
          	//1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
    		if(pHead==null) {return null;}
    		RandomListNode c=pHead;  //指针指向当前节点
    		while(c!=null) {
    			RandomListNode clone=new RandomListNode(c.label);
    			clone.next=c.next;
    			clone.random=null;
                c.next=clone;
    			c=clone.next;
    		}
    		
    		//2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
    		c=pHead;
    		while(c!=null) {
    			RandomListNode clone=c.next;
    			if(c.random!=null) {
    				clone.random=c.random.next;
    			}
    			c=clone.next;
    		}
    		
    		//3拆分链表,将链表拆分为原链表和复制后的链表
    		c=pHead;
    		RandomListNode cloneHead=pHead.next;
    		while(c!=null) {
    			RandomListNode clone=c.next;
    			c.next=clone.next;
    			if(clone.next==null) clone.next=null;
    			else {clone.next=c.next.next;}
    			c=c.next;
    		}
    		
    		
    		return cloneHead;
        }
    }
    

      

  • 相关阅读:
    jmeter脚本在非GUI模式下运行_增加请求和返回_记录
    scp从一台服务器复制文件到本台服务器
    crontab定时任务配置
    jmeter非GUI模式_单点运行
    jmeter非GUI模式_分布式运行
    Dede 查询附加表
    Dede 列表文章 自增
    dede密码忘记 的修改方法
    CSS 字体描边
    教你如何去掉点击链接时的虚线
  • 原文地址:https://www.cnblogs.com/kexiblog/p/11131082.html
Copyright © 2011-2022 走看看