首页 > 其他 > 详细

leetcode_Copy List with Random Pointer

时间:2015-05-17 16:48:40      阅读:179      评论:0      收藏:0      [点我收藏+]

描述:

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;
		List<RandomListNode>listOld=new ArrayList<RandomListNode>();//store the old node
		List<RandomListNode>listNew=new ArrayList<RandomListNode>();//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;
    }
}


leetcode_Copy List with Random Pointer

原文:http://blog.csdn.net/mnmlist/article/details/45789065

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!