Reversing a linked list 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;
 }

 if(!l-&gt;head) {
        printf("List is empty \n");
        return -1;
 }

 Node *prev_node = l-&gt;head;
 Node *curr_node = l-&gt;head-&gt;next;

 while(curr_node) {
        prev_node-&gt;next = curr_node-&gt;next;
        curr_node-&gt;next = l-&gt;head;
        l-&gt;head = curr_node;
        curr_node = prev_node-&gt;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 &lt;stdio.h&gt;

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

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

    return p; // new head
}

void print_list(Node* head)
{
    Node* t = head;
    while(t)
    {
        printf("%d\n", t-&gt;data);
        t = t-&gt;next;
    }
}

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

    Node* newHead = reverse_list(head);
    print_list(newHead);

    getchar();
}