Reverse single linked list using double pointers

aj.wh.ca 0 Tallied Votes 776 Views Share

This is a bit more tough than it sounds. well some one gave me this problem and I found this tricky not until I used recursion.

/***********************************************************
 * Author  : AJ
 * Demo    : Reverse a singly linked list using double 
 *           pointers
 * Concepts: Linked List creation, printing, recursion,
 *           double pointers in C        
 *          
 * Email   : aj.wh.ca@gmail.com
 * 
 * www.swiftthoughts.com
 **********************************************************/

#include<stdio.h>

struct link {
    int key;
    struct link *next;
};

struct link * create_llist(int max)
{
    struct link *head;
    struct link *ptr;
    int n = 0 ;

    if(max<1)return NULL;
    ptr=(struct link *)malloc(sizeof(struct link));
    head=ptr;

    while(n++ < max-1)
    {
        ptr->key=n;
        ptr->next=(struct link *)malloc(sizeof(struct link));
        ptr=ptr->next;
    }
    ptr->key=n;
    ptr->next=NULL;
    return head;
}

void reverse_llist(struct link *head,struct link **newHead)
{
    struct link **ptr=&head;

    if(*ptr == NULL || (*ptr)->next == NULL) return ;

    if((*ptr)->next->next != NULL)
        reverse_llist((*ptr)->next,newHead);
    else
        *newHead = (*ptr)->next ; 
    (*ptr)->next->next = *ptr ;
    (*ptr)->next = NULL;
}


print_list(struct link *head)
{
    struct link *a=head;
    if(!a) return ;
    while(a->next)
    {
        printf("  %d\t%x\n", a->key, a->next);
        a=a->next;
    }
    printf("  %d\t%x", a->key, a->next);
    printf("\n");
}

main(int argc, char*argv[])
{
    struct link *head;
    if(!argc) return ;
    head=create_llist(atoi(argv[1]));
    print_list(head);
    reverse_llist(head,&head);
    print_list(head);
}