剑指offer 复杂链表的复制
来源:互联网 发布:加工中心铣圆编程 编辑:程序博客网 时间:2024/05/17 23:58
题目:
原理:遍历链表,并复制每一个节点,将每个复制节点插到原来节点的后面,然后修改复制节点的random指针,最后将原链表与复制链表拆开!
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
实现:
/*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) { if(pHead==null)return null; RandomListNode pcur=pHead; while(pcur!=null){ RandomListNode temp=new RandomListNode(pcur.label); temp.next=pcur.next; pcur.next=temp; pcur=temp.next; } pcur=pHead; while(pcur!=null&&pcur.next!=null){ if(pcur.random==null)pcur.next.random=null; else pcur.next.random=pcur.random.next; pcur=pcur.next.next; } RandomListNode head=pHead.next; RandomListNode cur=head; pcur=pHead; while (pcur!=null&&pcur.next!=null){ pcur.next=pcur.next.next; if(cur!=null&&cur.next!=null) cur.next=cur.next.next; pcur=pcur.next; cur=cur.next; } return head; }}
原理:遍历链表,并复制每一个节点,将每个复制节点插到原来节点的后面,然后修改复制节点的random指针,最后将原链表与复制链表拆开!
易错点: 修改复制random指针时,注意空指针的判断,循环时注意pcur.next==null的判断,最后一定要将原链表与复制链表拆开!不然输出会出错!
阅读全文
0 0
- 【剑指offer】复杂链表的复制
- 剑指offer--复杂链表的复制
- 《剑指offer》复杂链表的复制
- 剑指offer:复杂链表的复制
- 剑指offer - 复杂链表的复制
- 剑指Offer--复杂链表的复制
- 剑指offer:复杂链表的复制
- 【剑指offer】复杂链表的复制
- 剑指offer-复杂链表的复制
- 剑指offer:复杂链表的复制
- 剑指offer:复杂链表的复制
- [剑指offer]复杂链表的复制
- 【剑指offer】复杂链表的复制
- 剑指offer|复杂链表的复制
- 《剑指offer》复杂链表的复制
- 剑指Offer:复杂链表的复制
- 剑指offer 复杂链表的复制
- 剑指offer-复杂链表的复制
- gz文件Header 解析
- 2016 Pacific Northwest Region Programming Contest—Division 2 Problem S — limit 1 second Gravity
- 历史上最详细的SpringBoot多数据源配置及使用流程
- WILL吃桃_KEY
- CSS学习笔记-3
- 剑指offer 复杂链表的复制
- 170720 逆向-misc-cctf(1)
- 吾爱破解160个crackme之002
- android调用H5显示加载中效果
- C语言编写smtp用户代理之协议操作
- Ubuntu16.04安装flash
- tcp四次挥手中FIN_WAIT2状态的最大时间是多长?
- adb操作命令详解及大全
- dijsktra最短路