Simon Guo
Simon Guo

Reputation: 2926

Reverse a linked list

The task is to reverse a linked list, so I build the linked list, then print is out, then all the reverse function, then print it our second time. However, the second print is empty. I think it is pointer issues here, any one can explain? thanks.

void reverseLinkedList(struct node** head) {
    struct node* curr, *prev, *temp;

    curr = *head;
    prev = NULL;

    while (curr) {
        temp = prev;
        prev = curr;        
        curr = curr->next;
        prev = temp;
    }
    *head = prev;
}

struct node* buildLinkedList(int list[], int len) {
    struct node* head = NULL;
    struct node* tail = NULL;
    struct node* node;
    int i;

    for (i = 0; i < len; i++) {
        node = (struct node*) malloc(sizeof(struct node));
        node->data = list[i];
        node->next = NULL;

        if (!head) {
            head = node;
        } else {
            tail->next = node;
        }
        tail = node;
    }
    return head;
}

void printLinkedList(struct node** head) {
    struct node* s = *head;
    while(s) {
        printf("%d\t", s->data);
        s = s->next;
    }
    printf("\n");
}

int main() {
    int list [6] = {6,7,8,3,4,5};
    struct node* header = NULL;
    header = buildLinkedList(list, 6);
    printLinkedList(&header);
    reverseLinkedList(&header);
    printLinkedList(&header);

}

The result I get from console is:

6       7       8       3       4       5   

where the second printLinkedList is printing nothing. Wondering where is the problem. Thanks.

Upvotes: 1

Views: 552

Answers (1)

Tony
Tony

Reputation: 10327

Looking at your function to reverse the list you have

while (curr) {
     temp = prev;
     prev = curr;        
     curr = curr->next;
     prev = temp;  // <<-- this resets prev to what it was before.
}

you never change the next pointer, but you change prev twice.

Upvotes: 6

Related Questions