Question: I am currently practicing pointers on my school break and below I written the method to reverse a doubly linked list, but when I hand it into an online test, it fails.

```
Node* Reverse(Node *head)
{
    int count = 0;
    struct Node *ptr = head;

    // return head if NULL
    if (head == NULL) {
        return head;
    }
    // if the list is only the head, then the reverse is just the head... so nothing changes
    if((head->next == NULL && head->prev == NULL)){
        return head;
    }

    //Come here if previous if statements fail, traverse the list until I reach tail which will become the
    // new head
    while(ptr->next != NULL){
        ptr = ptr->next;
        count++;
    }
    head = ptr; // this is the new head    
    //starting from tail all the way to head swap the "prev" and "next" of each node 
    struct Node *temp = ptr->next;

    for(int i = 0; i<count; i++){
        ptr->next = ptr->prev;
        ptr->prev = temp;
        ptr=ptr->next;
        temp= ptr->next;
        //count--;
    }

    return head;
}

```

I realize that it is probably smarter to reverse the list while I traverse it from head to tail, but I thought that was boring, so I decided to reverse it starting from the tail to head instead. I suspect there is an obvious error in my while loop or for loop, but I am unable to diagnose the error.

Answer: 
I think the error is here:

```
while(ptr->next != NULL){
    ptr = ptr->next;
    count++;
}

```

Let's say your linked list has 2 elements in it. Then that `while` loop will only iterate once, and `count` will be 1. When you get down to the `for` loop, it will also only iterate once, which means you will correctly reassign the pointers for the new head, but not the second element (previously the head).

If you initialize `count` to 1 instead of 0, it should correctly reflect the number of elements in the linked list and the `for` loop should execute correctly.

**Edit:** You will also have to restructure your `for` loop slightly to avoid a segfault at the end of the list:

```
Node* temp;

for (int i = 0; i < count; i++)
{
    temp = ptr->next;
    ptr->next = ptr->prev;
    ptr->prev = temp;
    ptr = ptr->next;
}

```
replace

```
for(int i = 0; i<count; i++){//i<count --> i<=count : Because Not counting last element
    ptr->next = ptr->prev;
    ptr->prev = temp;
    ptr=ptr->next;
    temp= ptr->next;//<-- bad
    //count--;
}

```

with

```
for(int i = 0; i <= count; i++){
    ptr->next = ptr->prev;
    ptr->prev = temp;
    temp = ptr;
    ptr = ptr->next;
}

```

or

```
while(ptr){
    ptr->next = ptr->prev;
    ptr->prev = temp;
    temp = ptr;//next prev
    ptr = ptr->next;
}

```