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;
        }
    }
    

      

  • 相关阅读:
    asp.net 对母版页的控件事件
    treeview操作集合
    使用GAppProxy时安全证书无效的解决办法
    向Excel模板中添加数据
    C# 重写 winform 关闭按钮
    完整ASP.Net Excel导入程序(支持2007)
    随笔二则
    标记枚举(flags)的使用
    System.Reflection.Missing.Value与Type.Missing
    Windows下Android源码下载方法
  • 原文地址:https://www.cnblogs.com/kexiblog/p/11131082.html
Copyright © 2011-2022 走看看