复杂链表的赋值

来源:互联网 发布:2010年总决赛数据 编辑:程序博客网 时间:2024/06/05 10:27

链表结构中,每个节点不仅有一条指向下一节点的next指针,同时含有一条rand指针,rand指针可能指向任何一个链表中的节点,请复制这种含有rand指针节点的链表。

 

方法1.创建一个没有rand时与复杂链表完全相同的链表,然后遍历原链表,给新链表rand复制。


方法2.



public class Solution {public RandomListNode Clone(RandomListNode head) {if (head == null) {return null;}RandomListNode cur = head;RandomListNode next = null;// copy node and link to every nodewhile (cur != null) {next = cur.next;cur.next = new RandomListNode(cur.label);cur.next.next = next;cur = next;}cur = head;RandomListNode curCopy = null;// set copy node randwhile (cur != null) {next = cur.next.next;curCopy = cur.next;curCopy.random = cur.random != null ? cur.random.next : null;cur = next;}RandomListNode res = head.next;cur = head;// splitwhile (cur != null) {next = cur.next.next;curCopy = cur.next;cur.next = next;curCopy.next = next != null ? next.next : null;cur = next;}return res;}}


原创粉丝点击