Qualcomm Interview Question Software Engineer / Developers
0of 0 votesLocate the node which is the m-th node from the end of a linked list. e.g. linked list has 100 nodes and m=5, it would be node 95.
struct node* getTheNode(struct node* pHead, int m)
{
struct node* pCurNode = pHead;
struct node* pRetNode = NULL;
for (int i=0; i<m; i++) {
if (pCurNode->pNext != NULL) pCurNode = pCurNode->pNext;
else return pRetNode;
}
pRetNode = pHead;
while (pCurNode->pNext != NULL) {
pCurNode = pCurNode->pNext;
pRetNode = pRetNode->pNext;
}
return pRetNode;
}
I THINK this is simpler.
struct node *getNode(struct node *pHead, int m)
{
struct node *pTemp=pHead, *mth=pHead;
int i=1;
while(pTemp)
{
pTemp = pTemp -> next;
if(i++>m) mth = mth->next;
}
return mth;
}

struct node* ptr1=head;
- Anonymous on September 20, 2009 Edit | Flag Replystruct node* ptr2=head;
int c=0;
while( ptr1->next!=NULL && c++<m )
ptr1=ptr1->next;
if(c<m)
abort();
while( ptr1->next!=NULL)
{
ptr1=ptr1->next;
ptr2=ptr2->next;
}
RETURN ptr2;