Reverse a singly linked list

Posted by Madhan on Stack Overflow See other posts from Stack Overflow or by Madhan
Published on 2009-11-26T04:34:25Z Indexed on 2010/03/27 19:13 UTC
Read the original article Hit count: 300

Filed under:
|
|

I would be wondered if there exists some logic to reverse the linked list using only two pointers.

The following is used to reverse the single linked list using three pointers namely p, q, r:

struct node
{
    int data;
    struct node *link;
};

void reverse()
{
    struct node *p = first,
                *q = NULL,
                *r;
    while (p != NULL)
    {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }
    q = first;
}

Is there any other alternate to reverse the linked list? what would be the best logic to reverse a singly linked list, in terms of time complexity?

© Stack Overflow or respective owner

Related posts about c

    Related posts about linked-list