Ebay Interview Question
Software Engineer / DevelopersCountry: United States
The code will do the job, however, you should always check for errors (in this case, null exception)
C doesn't have exceptions. I do check for next nodes being non null. while (frontRunner) is the same as while (frontRunner != NULL)
if asked to use only one pointer.. then..
we can use a circular queue of size 5, keep adding elements to it,
once end is reached, just print next element in queue.
(just an addition to question)
Why would that situation ever occur? If you don't have one pointer's worth of extra space, you most certainly don't have room for a circular buffer. Here that buffer could be only 5 pointers + a char in size, but still...
Java: [based on @eugene's logic]
public Node print5thNode(Node head)
{
Node front = head;
Node back = head;
int count = 0;
while(count<=5)
{
if (front.next == null)
return back;
front = front.next;
++count;
}
while(front.next != null)
{
front = front.next;
back = back.next;
}
return back;
}
public Integer five_th() {
if (size < 5) {
System.out.println("The number of array is not enough!");
return null;
}
Node ptr = head;
int step = 5;
while (step > 0) {
ptr = ptr.next;
step--;
}
Node ptr2 = head;
while (ptr != null) {
ptr = ptr.next;
ptr2 = ptr2.next;
}
return ptr2.value;
}
void InLinkedList(linkedListClass obj)
{
linkedListClass p1;
p1=obj;
linkedListClass p5=p1.next.next.next.next;
while (p5.next!=null)
{
if(p5.next==null)
{
while(p1.next!=null)
{
System.out.printf("the value of the node is : ",p1.data);
p1=p1.next;
}
}
else
{
p1=p1.next;
p5=p5.next;
}
}
}
Assuming the list has at least 5 nodes: advance a pointer (call it frontRunner) 5 times. Now create a pointer to the beginning of the linked list (call it result). Now, advance both pointers one-by-one until frontRunner== NULL. e.g.:
- eugene.yarovoi January 08, 2012