Tuesday, August 28, 2007

Reverse a linked list

Here is the iterative and recursive solution:

struct linkedList{
int element;
struct linkedList *next;
};

typedef struct linkedList* List;

List reverseList(List L)
{
List tmp, previous=NULL;

while(L){
tmp = L->next;
L->next = previous;
previous = L;
L = tmp;
}
L = previous;
return L;

}

List recursiveReverse(List L)
{
List first, rest;
if(!L)
return NULL;
first = L;
rest = L->next;
if(!rest)
return NULL;
rest = recursiveReverse(rest);
first->next->next = first;
first->next = NULL;
L=rest;

return L;
}




Powered by ScribeFire.

No comments:

Post a Comment