Amazon Interview Question
Software Engineer / DevelopersHi
structure of the linklist
struct lnlst{
int info;
struct lnlst *next;
};
function to reverse using iteration:
struct lnlst* reverse(struct lnlst *ls)
{
struct lnlst *temp,*prev,*current;
prev=0;
temp=0;
current=ls;
while(current)
{
temp=current->next;
current->next=prev;
prev=current;
current=temp;
}
return(prev);
}
Hi,
this can also be written as:
struct lnlst* reverse(struct lnlst *ls)
{
struct lnlst *temp,*prev,*current;
prev=0;
temp=0;
current=ls;
if(current == NULL)
return;
do
{
temp=current->next;
current->next=prev;
prev=current;
current=temp;
}while(current)
return(prev);
}
if there is any problem plz let me know
shouldn't use recursion, because the stack would use too much memory.
I would do it with three pointers. Pseudo follows (assuming list ends when next points to null).
- zsepi March 01, 2007