1
votes

im trying to reverse a double linked list without using any extra pointer.I only have head pointer pointing to the first node of my double linked list.

here is my function to reverse the linked list:

int reverse(){
if(head==NULL || head->next==NULL){
    return 0;
}
else{
    head->prev=head->next;
    head->next=NULL;
    head->prev->prev=head->prev->next;
    head->prev->next=head;
    head=head->prev;
    while(head->prev==NULL){
        head->prev->prev=head->prev->next;
        head->prev->next=head;
        head=head->prev;
    }
}}

if my linked list have data 1,2,3,4,5 and after running the reverse function ,when i'm trying to display the data i'm getting output: 2,1 (instead of 5,4,3,2,1)

1
if(head==NULL && head->next==NULL) That will cause a NULL pointer access when head is a NULL. You probably want || instead of && there. - kaylum
Why not just iterate over your list swapping next and prev and when you are done, swap head and tail? - David C. Rankin
@DavidC.Rankin I think the challenge is doing that without using any extra pointers. Not sure whether that is a hard requirement or something OP thinks is a good idea for some reason. - kaylum
You could always use the XOR hack to swap and follow the prev pointer afterwards to iterate. - David C. Rankin
@user3629249 i defined head in structure the only error i have ,is in while statement while(head->prev==NULL) after correcting the error my program compile and works fine - taretor

1 Answers

0
votes

there is a error in while statement while(head->prev==NULL) the correct code is while(head->prev!=NULL)

so the correct code of the function is:

int reverse(){
if(head==NULL || head->next==NULL){
    return 0;
}
else{
    head->prev=head->next;
    head->next=NULL;
    head->prev->prev=head->prev->next;
    head->prev->next=head;
    head=head->prev;
    while(head->prev!=NULL){
        head->prev->prev=head->prev->next;
        head->prev->next=head;
        head=head->prev;
    }
}}