剑指offer:复杂链表的复制 为什么我的程序是错的?
题目为:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
参考的代码是:
/*public class RandomListNode {int label;RandomListNode next = null;RandomListNode random = null;RandomListNode(int label) {this.label = label;}}*/publicclassSolution {publicRandomListNode Clone(RandomListNode pHead) {if(pHead == null) { returnnull; }RandomListNode head = newRandomListNode(pHead.label) ;RandomListNode temp = head ;while(pHead.next != null) {temp.next = newRandomListNode(pHead.next.label) ;if(pHead.random != null) {temp.random = newRandomListNode(pHead.random.label) ;}pHead = pHead.next ;temp = temp.next ;}returnhead ;}}
我的代码是:
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null)
return null;
RandomListNode head=new RandomListNode(pHead.label);
RandomListNode temp=head;
while(head.next!=null){
temp.next=new RandomListNode(head.next.label);
if(temp.random!=null){
temp.random=new RandomListNode(head.random.label);
}
head=head.next;
temp=temp.next;
}
return pHead;
}
}
我觉得几乎是一样的 为什么我的是错的 上面那个代码是对的呢?#Java工程师##安卓工程师#
