Amazon Interview Question
Software Engineer / Developerspublic void displayLisReversed(Link currNode)
{
Link pCurrent = currNode; //start at beginning of list
if (pCurrent.pNext != null) //until end of list,
{
displayLisReversed(pCurrent.pNext);
}
pCurrent.displayLink();
}
public class Link
{
public int iData; //data item
public double dData; //data item
public Link pNext; //ptr to next link in list
//-------------------------------------------------------------
public Link(int id, double dd)
{
iData = id;
dData = dd;
pNext = null;
}
//-------------------------------------------------------------
public void displayLink() //display ourself {22, 2.99}
{
Console.WriteLine("iData = " + dData);
}
//-------------------------------------------------------------
}
Tested and working code, should take care of edge case tests.
Node MakeSingleLinkedListReverse(Node currentNode)
{
Node previousNode = null;
Node nextNode = null;
while (currentNode != null)
{
nextNode = currentNode.NextNode;
currentNode.NextNode = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
<pre lang="" line="1" title="CodeMonkey95834" class="run-this">struct List
- Anonymous June 12, 2011{
int data;
struct List *next;
};
struct List* Reverse(struct List* head)
{
struct List *temp;
if(head==NULL)
return NULL;
if(head->next==NULL)
return head;
temp=reverse(head->next);
head->next->next=head;
return temp;
}</pre><pre title="CodeMonkey95834" input="yes">
</pre>