• 25、复杂链表的复制


    一、题目

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

    二、解法

     1 public class Solution {
     2     //递归
     3     /*public RandomListNode Clone(RandomListNode pHead)
     4     {
     5         if(pHead == null) return null;
     6             RandomListNode newHead = new RandomListNode(pHead.label);
     7             newHead.random = pHead.random;
     8             newHead.next = Clone(pHead.next);
     9             return newHead;
    10     }*/
    11     
    12     public RandomListNode Clone(RandomListNode pHead){
    13          if(pHead == null)
    14              return null;
    15          RandomListNode pCur = pHead;
    16          //1、复制原结点的next,如原来是A->B->C 变为 A->A'->B->B'->C->C'
    17          while(pCur != null){
    18              RandomListNode node = new RandomListNode(pCur.label);
    19              node.next = pCur.next;//将node的next指向pCUr的next  A'->B  A->B
    20              pCur.next = node;//将pCur.next指向node A->A'->B
    21              pCur = node.next;//将pCur指向node.next 下次辅助B
    22          }
    23          pCur = pHead;//将pCur指向pHead
    24          //2、复制random指针,  pCur是原来链表的结点,pCur.next是复制pCur的结点
    25          while(pCur != null){
    26              if(pCur.random != null)//如果pCur.random不为空
    27                 //将pCur的random指针的next就是pCur.next的random指针指向的结点
    28                  pCur.next.random = pCur.random.next;
    29              pCur = pCur.next.next;//移动pCur指针
    30          }
    31          //新建一个head结点,指向pHead的next结点,即指向拆分链表的头结点
    32          RandomListNode head = pHead.next;
    33          //新建一个cur结点,指向拆分链表的head头结点
    34          RandomListNode cur = head;
    35          //将pCur指向头结点
    36          pCur = pHead;
    37          //3、拆分链表
    38          while(pCur != null){
    39              pCur.next = pCur.next.next;
    40              if(cur.next != null)//cur.next有可能为空,当最后一个结点的时候
    41                  cur.next = cur.next.next;
    42              cur = cur.next;//后移指针
    43              pCur = pCur.next;//后移指针
    44          }
    45          return head;
    46      }
    47 }
  • 相关阅读:
    flask 第三方组件
    Flask基础与进阶
    odoo10 视图
    odoo10 ORM操作
    odoo10基础
    字典的setdefault方法
    redis常用操作
    git常用命令与操作
    vue_axios
    odoo 权限设置
  • 原文地址:https://www.cnblogs.com/fankongkong/p/7452114.html
Copyright © 2020-2023  润新知