-5
void reverse(node *pointer) {
    node *head, *curr;
    head = pointer;
    curr = head;
    while (head != NULL) {
        while (curr -> next != NULL) {
            curr = curr -> next;
        }
        printf("%d", curr -> data);
        free(curr);
        curr = head;
    }
}

I don't know what's wrong with the code it prints only the last node of the linked list while trying to reverse it.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Vivek M.
  • 1
  • 1
  • 1
  • 7
    why use `free` for reversing a list? this does not make any sense.... – Netwave Aug 02 '16 at 10:34
  • 1
    You have a major unrelated problem: You call `free` thereby making all the nodes in the list invalid. – Some programmer dude Aug 02 '16 at 10:34
  • 1
    Possible duplicate of [How to reverse a singly linked list using only two pointers?](http://stackoverflow.com/questions/1801549/how-to-reverse-a-singly-linked-list-using-only-two-pointers) – xenteros Aug 02 '16 at 10:39

2 Answers2

4

Simply:

node *reverse(node *head){
    node *result = NULL;
    while (head) {
        node *next = head->next;
        head->next = result;
        result = head;
        head = next;
    }
    return result;
}
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
3

You will not be able to see the output of the above function mainly for two reasons

  1. Passing by value instead of reference.
  2. No print statement inside the function. The effect of this function will be destroyed as soon as it comes out of the function.

In code:

void reverse(struct node** head_ref) {
    struct node* prev  = NULL;
    struct node* current = *head_ref;
    struct node* next;
    while (current != NULL) {
        next  = current->next;  
        current->next = prev;   
        prev = current;
        current = next;
    }
    *head_ref = prev;
}
Simon Rigét
  • 2,757
  • 5
  • 30
  • 33
Shravan40
  • 8,922
  • 6
  • 28
  • 48