vitorsouza
vitorsouza

Reputation: 1

Reverse linked list C

I've been trying to reverse a linked list without copy, but it only prints the first element of the list.

typedef struct list{
  int info;
  struct list *next;
}TLSE;

void reverse_linked_list(TLSE *list){

    TLSE *prev = NULL;
    TLSE *curr = list;
    TLSE *next = NULL;

    while(curr != NULL){
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }

}

If I have a list like: 1 3 7, I'd like to reverse and print 7, 3, 1.

Upvotes: 0

Views: 69

Answers (2)

Lazt Omen
Lazt Omen

Reputation: 40

If you are expecting to use the result outside of that function you need to pass the list as a double pointer and assign current as the head of the list otherwise you keep pointing to the first element which is now the last one and the next element would be null.

void reverse_linked_list(TLSE **list){

    TLSE *prev = NULL;
    TLSE *curr = *list;
    TLSE *next = NULL;

    while(curr != NULL){
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    
    *list = prev;
}

Upvotes: 1

Aconcagua
Aconcagua

Reputation: 25516

The point is that the pointer you pass to the function remains unchanged outside the function:

struct list* l = /* ... */;

reverse_linked_list(l); // leaves l unchanged!!!
print_linked_list(l); // l still at former head, which now is the tail

You now can either return the new head of the list:

TLSE* reverse_linked_list(TLSE *list)
{
    // ...

    return prev; // this is the value to the latestly used node;
                 // curr in contrast now is NULL!
}

l = reverse_linked_list(l);
print_linked_list(l);

or you accept a pointer to pointer instead and adjust it appropriately:

void reverse_linked_list(TLSE **list)
{
    TLSE *curr = *list;
    // ...

    *list = prev;
}

reverse_linked_list(&l);
print_linked_list(l);

Upvotes: 2

Related Questions