Here is sample code to reverse a doubly linked list: using both, iterative and recursive, method is
given below:
node* rev_dlist(node* n)
{
while (n) {
node* t = n->next;
n->next = n->prev;
n->prev = t;
if (!t) break;
n = t;
}
return n;
}
Using recursion, the above can be implemented as:
node* rev_dlist(node* n)
{
if (n) {
node* t = n->next;
n->next = n->prev;
n->prev = t;
if (!t) return n;
return rev_dlist(t);
}
return 0;
}
given below:
node* rev_dlist(node* n)
{
while (n) {
node* t = n->next;
n->next = n->prev;
n->prev = t;
if (!t) break;
n = t;
}
return n;
}
Using recursion, the above can be implemented as:
node* rev_dlist(node* n)
{
if (n) {
node* t = n->next;
n->next = n->prev;
n->prev = t;
if (!t) return n;
return rev_dlist(t);
}
return 0;
}
Comments
Post a Comment
https://gengwg.blogspot.com/