Circular linked list

My while loop is not working. Please suggest

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
  #include<iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};
typedef node *list;

int main()
{
        int dat;
        char ch;
        list first, last;
        first=NULL;
        last=NULL;
        cout<<"Do you want to enter data?(y/n)"<<endl;
        cin>>ch;
        while(ch=='y'||ch=='Y')
        {
            cout<<"Enter data"<<endl;
            cin>>dat;
            if(last==NULL)
            {
                last=new node;
                last->data=dat;
                last->next=last;
                first=last;
            }
            else
            {
                last->next=new node;
                last->next->data=dat;
                last->next->next=first;
            }
            cout<<"Enter more data?(y/n)"<<endl;
            cin>>ch;

        }
        cout<<"Displaying the ciruclar linked list"<<endl;
        //last=first;
        while(first!=last)
        {
            cout<<"Data is "<<last->data<<"\tAt Address "<<last->next<<endl;
            last=last->next;
        }
        return 0;
}

I ran your program: http://ideone.com/wiwCkX
Notice the debug output I added just before the while loop. In the output, you see that they are at the same address. I tried a do-while loop but it only output 1 and 4 and then ended. Are you sure your list is being constructed properly?
Last edited on
As LB pointed out, your list is not getting built correctly.

After adding new node, you should also update last to point to the new node:

1
2
last->next->next=first;
last = last->next;


Also I would recommend you to delete dynamically allocated memory before end of program. At present you would leak memory on program exit.
Last edited on
Topic archived. No new replies allowed.