注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
LeetCode上名为 Copy List with Random Pointer的题目。
题目要求是:
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.
我的想法是借助哈希表来实现,每次在新的List中添加一个Node之后就按照<OldNode, NewNode>的pair存进哈希表里面,后面再为新的LinkedList创建Node的时候,看看next,random两个Point所指向的Node是不是已经在先前创建过了,如果是就直接用创建好的,不然就新建一个。以下是我的实现代码:
/**
* 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;
RandomListNode newhead = new RandomListNode(head.label);
if (head.next == null)
{
newhead.next = head.next;
newhead.random = head.random;
return newhead;
}
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
map.put(head, newhead);
map.put(null,null);
RandomListNode pOld = head, pNew;
while(pOld!=null)
{
if (map.containsKey(pOld))
pNew = map.get(pOld);
else
{
pNew = new RandomListNode(pOld.label);
map.put(pOld, pNew);
}
if (map.containsKey(pOld.next))
pNew.next = map.get(pOld.next);
else
{
pNew.next = new RandomListNode(pOld.next.label);
map.put(pOld.next, pNew.next);
}
if (map.containsKey(pOld.random))
pNew.random = map.get(pOld.random);
else
{
pNew.random = new RandomListNode(pOld.random.label);
map.put(pOld.random, pNew.random);
}
pOld = pOld.next;
}
return newhead;
}
}
没有Accept,报错如下:
/*
Submission Result: Wrong Answer
Input: {-1,-1}
Output: Random pointer of node with label -1 points to a node from the original list.
Expected: {-1,-1}
*/
求哪位大神给我解答一下,问题出在哪里啊? 纠结了一下午了>< |