Synopsys R&D Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Kindly let me know what is the problem with the approach below, it is causing runtime error.
struct Node* NthFromLast(struct Node *head, int N) {
static int count =0;
if (!head)
return NULL;
NthFromLast(head->next, N);
if (++count == N)
return head;
else
return NULL;
return NULL;
}
It returns NULL instead of the nth node, or the head of the list if there are n elements in it.
Thanks, I got this modified code
struct Node* rec_nth(struct Node* node, int n) //n being the 'nth' element index from the end
{
static int count;
static Node* soln = NULL;
if(node->next == NULL)
{
count = 0;
return node;
}
rec_nth(node->next,n);
if (++count == n)
{
soln = node;
}
return soln;
}
nthnode(node *l,int n,node *q) //q will be passed null at starting
{ if(n==0)
return q
else
{
node *p=l;
while(p->next!q)
{
p=p->next;
}
q=p;n=n-1;
nthnode(l,n,q)
}
}
struct Node* NthLast(struct Node* head, int n)
{
//Non Recursive
//
//point first pointer to start
//move first pointer to nth node
//point second pointer to start
//move both pointer towards end until first reach to last node
//second pointer is nth last node
//
struct Node *ptr1 = NULL;
struct Node *ptr2 = NULL;
if (n < 0) return NULL;
ptr1 = head;
while(ptr1 != NULL && n > 0)
{
ptr1 = ptr1->next;
n--;
}
if (ptr1 == NULL) return NULL;
ptr2 = head;
while(ptr1->next != NULL)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return ptr2;
}
check the pseudo code:
- Anonymous October 19, 2012test(struct node *head,int n) {
int count=0;
node *nthnode= nthnode(struct node *head,int n);
return(nthnode);
nthnode(struct node *head,int n) {
if(head==null)
return
else
head=head->next;
nthnode(struct node *head,int n);
count++;
if(count==n);
return head;
}
}
}