zoukankan      html  css  js  c++  java
  • 每天一道算法题目(20)——复杂链表的拷贝

    题目:

         输入复杂链表如图,复制该链表。




    思路:

           如图。传统的做法是先复制next指针部分,然后对于每个节点的random部分,则需要遍历整个链表查找对应节点。时间复杂度为O(n.^2)。时间这里总结一种时间复杂度为O(n)空间复杂度为O(1)的方法。

           第一步。简单复制next指针部分,并将拷贝节点和源节点链接一起。结果如下图:

           第二步。遍历链表,遇到random指针非空的,则其对应拷贝节点,也就是他的下一节点的random应该指向当前节点random指向的下一节点。例如A指向C,则A*必然指向C*,以此类推。

           第三步。拆分节点,偶数节点串接为拷贝链表,奇数节点串接为原链表。



    代码:

    typedef struct Tree{
    	Tree* next;
    	Tree* random;
    }* node;
    
    node copy(node head){
    	if(!head)
    		return NULL;
    
    	//复制链表
    	node temp=head;
    	node copyNode=NULL;
    	while(temp){
    		copyNode=new Tree();
    		copyNode->next=temp->next;
    		temp->next=copyNode;
    		temp=copyNode->next;
    	}
    
    	//复制随机指针
    	temp=head;
    	while(temp){
    		if(!temp->random)
    			temp->next->random=temp->random->next;
    		temp=temp->next->next;
    	}
    
    	//将偶数链表拆分出来连接到一起即为链表的拷贝,当然应该将奇数部分重新整理还原
    	temp=head;
    	node copyHead=NULL;
    	copyNode=copyHead=temp->next;
    	temp->next=copyNode->next;
    	temp=temp->next;
    	while(temp){
    		copyNode->next=temp->next;
    		copyNode=copyNode->next;
    		temp->next=copyNode->next;
    		temp=temp->next;
    	}
    	return copyHead;
    }




  • 相关阅读:
    JSP 中文乱码显示处理解决方案
    jsp的9大对象
    获取各种路径
    输出自绘制图片
    Emmet基本使用方法
    <input type="file" />浏览时只显示指定文件类型
    使用dockerfile文件创建image
    gunicorn 访问日志配置与项目启动
    制作符合自己需求的镜像 docker image
    linux 查看系统信息
  • 原文地址:https://www.cnblogs.com/engineerLF/p/5393012.html
Copyright © 2011-2022 走看看