reversing doubly linked list

.exe has stopped working...what is the problem with my last while loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 #include <iostream>
using namespace std;
struct node
{
    struct node *previous;
    int data;
    struct node *next;
}*head=NULL,*last=NULL,*temp;
int main()
{
    int dat;
    char ch;
    cout<<"Enter  data?(y/n)"<<endl;
    cin>>ch;
    if(ch=='y'|| ch=='Y')
    {
        cout<<"Enter the data to be inserted"<<endl;
        cin>>dat;
        last=new node;
        last->data=dat;
        last->previous=NULL;
        last->next=NULL;
        head=last;
        cout<<"Enter more data"<<endl;
        cin>>ch;
    }
    while(ch=='y'|| ch=='Y')
    {
        cout<<"Data?"<<endl;
        cin>>dat;
        last->next=new node;
        last->next->data=dat;
        last->next->previous=last;
        last->next->next=NULL;
        last=last->next;
        cout<<"Enter more data?(y/n)"<<endl;
        cin>>ch;
    }
   /*while(head!=NULL)
    {
        cout<<head->data;
        head=head->next;
        cout<<"\n";
    }*/
    cout<<"The reversed list is"<<endl;
    while(head!=NULL)
    {
        temp=head->next;
        head->next=head->next;
        head->next=head->next->previous;
        head->next->previous=temp;
        head=head->next;
    }
    temp=head;
    head=last;
    last=temp;
    while(head!=NULL)
    {
        cout<<head->data;
        head=head->previous;
        cout<<"\n";
    }


}
It's not your last while loop causing the issue, it's the penultimate while loop. You seem to be doing a lot of unnecessary swapping around.

Do you need to actually change the order of the list, or just print the reversed list? If it's the latter, you could easily do it by doing this:
1
2
3
4
5
6
7
node *curr = last;

while( curr->previous )
{
    std::cout << curr->data;
    curr = curr->previous;
}


You could add an extra layer of safety by making sure curr isn't null as well.
Last edited on
Topic archived. No new replies allowed.