by mbrubeck · 16y ago · 0 comments
The recursive solution does not work. It never sets “next” to NULL for the original head of the list, so now the list ends with a cycle.
The non-recursive solution does not work either. It never assigns anything to “previous”, so it always returns NULL and sets all of the “next” pointers to NULL.
This is easy to see if you actually compile and run both of these on some sample input:
#include <stdio.h>
typedef struct Node {
struct Node *next;
int value;
} Node;
Node * reverse( Node * ptr )
{
Node * temp;
if(ptr->next == NULL) {
return ptr;
} else {
temp = reverse(ptr->next);
ptr->next->next = ptr;
return temp;
}
}
Node * ireverse( Node * ptr )
{
Node * temp;
Node * previous = NULL;
while(ptr != NULL) {
temp = ptr->next;
ptr->next = previous;
ptr = temp;
}
return previous;
}
void print(Node *head) {
Node *curr;
for (curr = head; curr != NULL; curr = curr->next) {
printf("%d\n", curr->value);
}
}
main() {
Node a, b, c;
a.value = 1;
a.next = &b;
b.value = 2;
b.next = &c;
c.value = 3;
c.next = NULL;
printf("Iterative:\n")
print(ireverse(&a));
a.value = 1;
a.next = &b;
b.value = 2;
b.next = &c;
c.value = 3;
c.next = NULL;
printf("Recursive:\n")
print(reverse(&a));
}It's just a blog. There's effectively no barrier to entry. :)