I implemented reversing a linked list in iterative way, just by knowing we need 3 pointers and I have never seen a code before, when I coded. I ran this code and tested it, it works fine. Even for null element and one element. But all the implementations on net have slightly different code. I was just wondering, how my algorithm is.

Do you guys see any major concern in my implementation?

``````int reverse(List *l) {

if(!l) {
printf("List is NULL \n");
return -1;
}

printf("List is empty \n");
return -1;
}

while(curr_node) {
prev_node->next = curr_node->next;
curr_node = prev_node->next;
}

return 0;
}
``````
-

If you don't care about the origin list, we can use the head of it as the iterator, You should return the new head after reverse, or the new list will lost.

``````#include <stdio.h>

struct Node
{
int data;
Node* next;
Node(int value, Node* ptr):data(value), next(ptr){}
};

// Reverse list and return the new head
{
Node* p = NULL;
while(q)
{
Node* t = q->next;
q->next = p;
p = q;
q = t;
}

}

{
while(t)
{
printf("%d\n", t->data);
t = t->next;
}
}

void main()
{
Node* head = new Node(1, NULL);
for(int i = 2; i < 10; ++i)
{
p->next = new Node(i, NULL);
p = p->next;
}

getchar();
}
``````
-

Try this code, it's a bit easier to follow. Also, you define the return type as int, but you're not returning anything meaningful, so you should change the function to void.

``````void reverse(Node* & node)
{
if(!node)
{
cerr << "The node doesn't exist \n" << endl;
return;
}

Node* curr;
Node* prev = NULL;

while(node != NULL)
{
curr = node->next;
node->next = prev;
prev = node;
node = curr;
}
}
``````
-
You needn't to check node in the if block, since you did it in the while loop. –  zdd Oct 20 '12 at 7:19
Good call. The error message is unnecessary I'd say. –  dmastylo Oct 20 '12 at 8:43
This code doesn't work. The `node` pointer is passed by value so the caller's copy of the pointer is unchanged. The typical solution is to return the new `head` value (see zdd's answer). –  Blastfurnace Oct 20 '12 at 16:03
Yeah that was my bad, forgot to add the by ref. –  dmastylo Oct 20 '12 at 19:31