// reverse linked list with recursion
node* reverse(node *prev, node *cur){
// occurs only for last_node->next
if( cur == null )
return prev;
node *temp = cur->next;
cur->next = prev;
return reverse(cur, temp);
}
int main(){
node *p = /* linked list */;
p = reverse(NULL, p);
return 0;
}
// reverse linked list without recursion
int main() {
NODE *head = /* given list */, *cur = head, *prev = NULL, *temp = NULL;
while( cur -> next ) {
temp = cur -> next;
cur -> next = prev;
prev = cur;
cur = temp;
}
head = cur; // end of iteration, cur will point to last
return 0;
}
Friday, January 21, 2011
Reverse linked list
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment