Reversing a linked list in C, code troubles

I attempted to reverse a simple linked list (containing 0, 1, 2, 3...9) in c, but my code won't fully function. Any ideas as to what i'm doing wrong?

I'm pretty sure I had the reverse function right, the main thing i'm having trouble with is figuring out what to place into the argument of the reverse() function. This program is very close to functioning, it compiles but it doesn't print the reversed list so i'm not sure what i'm doing wrong. Any help that someone can give would be greatly appreciated! :)

CODE:

#include <stdio.h>
#include <stdlib.h>

struct node;
typedef struct node Node;

struct node
{
    int data;
    Node* next;
};

void reverse(Node* *);

int main(int argc, char* argv[])
{
    Node* head = NULL;
    int i;
    Node* temp;

    //set up a test list with values 9->8->7->...->0
    for (i = 0; i < 10; i++)
    {
        temp = (Node*)malloc(sizeof(Node));
        if (temp == NULL)
        {
            printf("out of memory?\n");
            exit(1);
        }
        temp->data = i;
        temp->next = head;
        head = temp;
    }

    reverse(head);

    //print the reversed list.
    temp = head;
    while (temp != NULL)
    {
        printf("%d\n", temp->data);
        temp = temp->next;
    }

    return 0;
}

void reverse(Node* *head)
{
    Node* pre = NULL;
    Node* cur = NULL;
    Node* nex = NULL;

    pre = cur = nex = *head;
    pre = pre->next->next;
    cur = cur->next;
    nex->next = NULL;
    cur->next = nex;

    while(pre != NULL)
    {
        nex = cur;
        cur = pre;
        pre = pre->next;
        cur->next = nex;
    }

    *head = pre;

}  

1 answer

  • answered 2018-10-11 20:45 Fred Larson

    In fact, your reverse() function is not correct. It always assigns *head to NULL. Always.

    while(pre != NULL)
    {
        nex = cur;
        cur = pre;
        pre = pre->next;
        cur->next = nex;
    }
    

    The only way for this loop to terminate is if pre is NULL. Then you use that to assign to *head:

    *head = pre;
    

    So your result will always be an empty list. Try setting it to cur instead.

    Also, your function will not work on empty of single-entry lists. And as the comments point out, you need to pass the address of your head pointer -- reverse(&head).