描述:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
思路:
1.首先根據舊鏈表的值創建一個新的鏈表並分別將舊鏈表和新鏈表存儲到listOld和listNew中。
2.然後根據舊鏈表中index位置的結點的random指針所指向的位置,找出舊鏈表指針所指向結點在listOld中的index,也即listNew中的newIndex
3.把新鏈表中的index位置的結點指向newIndex位置的結點,問題得解!
代碼:
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */ public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if(head==null) return null; ListlistOld=new ArrayList ();//store the old node List listNew=new ArrayList ();//store the new node RandomListNode newHead=new RandomListNode(0); RandomListNode pListNode=head,curListNode=newHead; while(pListNode!=null)//create the new LinkList && store the old node to listOld&store the new node to listNew { listOld.add(pListNode);//store the old node RandomListNode qListNode=new RandomListNode(pListNode.label ); listNew.add(qListNode);//store the new node curListNode.next=qListNode; curListNode=qListNode; pListNode=pListNode.next; } RandomListNode qListNode=newHead.next,temp=null; pListNode=head; int indexOld=0; while(pListNode!=null)//get the index of pListNode.random ,then put the node of indexOld to che random of the current newList { temp=pListNode.random; if(temp!=null) { indexOld=listOld.indexOf(pListNode.random);//get the index of pListNode.random qListNode.random=listNew.get(indexOld);//put the node of indexOld to che random of the current newList } else { qListNode.random=null; } pListNode=pListNode.next; qListNode=qListNode.next; } return newHead.next; } }