Tuesday, October 14, 2014

#codingexercise
A linked list is given such that each node  additionally  points to a random other node in the list. Perform a deep copy.
Node* deepCopy(node* source)
{
 if (source == NULL) return NULL;
 Node* clone = deepCopy(source);
 Node* curSrc = source;
 Node* curDest = clone;
while (curSrc)
{
  if (curSrc->other == NULL) {curDest->other = NULL; continue;}
  int offset = relativePos(curSrc, curSrc->other, source);
  if (offset <0)
  {
    Node* dest = clone;
    for (int i = offset+1; i < 0 && dest; i = i + 1)
             dest = dest->next;
   curDest->other = dest;
  }
  else
  {
     Node* dest = curDest;
     for (int i =0; i< offset && dest; i++)
             dest = dest->next;
     curDest->other = dest;
  }
  curSrc = curSrc->next;
  curDest = curDest->next;
}
return clone;
}

Node* shallowCopy (Node* source)
{
If (!source) return NULL;
Node* ret = new Node ();
If (!ret) throw out_of_memory;
Ret->next = shallowCopy (source->next);
Return ret;
}

Int relativePos (node* source, node* target, node* head)
{
If (Source == target) Return 0;
Int I = 1;
while ( source && source->next && source->next != target)
{
Source = source->next;
I++;
}
If (source->next == target) return i;
I = -1;
if (head == target) return i;
While (head && head->next && head->next != target)
{
Head = head->next;
I =i-1;
}
Return i;
}

No comments:

Post a Comment