zoukankan      html  css  js  c++  java
  • 复杂链表的复制-剑指Offer

    复杂链表的复制

    题目描述

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。

    思路

    分三步(分而治之)

    1. 将链表复制下来追加到每个元素的后面,例如A->A'->B->B'->C->C'...
    2. 复制每个元素的random指针
    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)
        {
            cloneNodes(pHead);
            cloneRandom(pHead);
            return reconnectNode(pHead);
        }
        // 复制链表追加到每个元素的后面
    	public void cloneNodes(RandomListNode pHead) {
    		RandomListNode temp = pHead;
    		while (temp != null) {
    			RandomListNode newNode = new RandomListNode(temp.label);
    			newNode.random = null;
    			newNode.next = temp.next;
    			
    			temp.next = newNode;
    			temp = newNode.next;
    		}
    	}
        // 复制每个元素的random指针
    	public void cloneRandom(RandomListNode pHead) {
    		RandomListNode temp = pHead;
    		while (temp != null) {
    			if (temp.random != null) {
    				temp.next.random = temp.random.next;
    			} else {
    				temp.next.random = null;
    			}
    			temp = temp.next.next;
    		}
    	}
        // 从整个链表中抽离出来我们复制的链表
    	public RandomListNode reconnectNode(RandomListNode pHead) {
    		RandomListNode pNode = pHead;
    		RandomListNode newHead = null;
    		RandomListNode newNode = null;
    		if (pNode != null) {
    			newHead = pNode.next;
    			newNode = newHead;
    			pNode.next = newNode.next;
    			pNode = pNode.next;
    		}
    		while (pNode != null) {
    			newNode.next = pNode.next;
    			newNode = newNode.next;
    			pNode.next = newNode.next;
    			pNode = pNode.next;
    		}
    		return newHead;
    	}
    }
  • 相关阅读:
    EditPlus等编辑器选中列(块)的方法
    构建Springboot项目的3种方式
    STS各版本下载
    Spring Boot 各版本的Java版本要求
    Maven安装
    Linux find命令:在目录中查找文件(超详解)
    rpm命令怎么指定安装位置
    CentOS6.8安装RabbitMQ
    codeforces459D:Pashmak and Parmida's problem
    codeforces 705B:Spider Man
  • 原文地址:https://www.cnblogs.com/rosending/p/5628198.html
Copyright © 2011-2022 走看看