Apr 20, 2011

reverse a list recursively and nonrecursively

reverse(h)
{
/*
* 1->2->p ...
* 2->1->p ...
*/
if(!h && !h->next)
return

t = h->next
h->next = NULL
while(t)
{
next = t->next
t->next = h
h = t
t = next
}
}



reverse(h)
{
/*
* 1->2->3->4
* 4->3, 1->2->3
* 4->3->2, 1->2
* 4->3->2->1
*/
if(!h && !h->next)
return

first = h
next = first->next

reverse(next)

first->next->next = first
fisrt->next = 0
h = next
}

No comments: