Inserting node at beggining of a linked list.

The program goes into an infinite loop. I can't really seem to understand why. The logic is simple. My implementation as far as i can see is pretty accurate. Any help would be appreciated.


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;
void Insert(int x);
void Print();
struct Node
{
    int data;
    Node *link;
};
Node *head;
int main()
{
    head = NULL; // List Is Empty
    int x,i,n;
    cout << "?";
    cin >> n;
    for (i = 0 ; i < n ;++i)
    {
        cin>>x;
        Insert(x);
        Print();
    }
    return 0;
}
void Insert(int x)
{
    Node *temp = new Node;
    temp -> data = x;
    temp -> link = NULL;
        if (head == NULL)
        {
            head = temp;
        }
        else
            if (head!= NULL)
        {
            temp -> link = head ;
            head =temp;
        }
}
void Print()
{
 Node *ptr;
 ptr = head;
    while(ptr)
    {
        ptr -> link = ptr;
        cout << endl << ptr -> data;
    }
}
Your while loop will run until ptr is invalid. Where inside that while loop does the validity of ptr change? Nowhere. So when will the ptr value become invalid? Never. So when will the while loop stop? Never.
Oh freaking god thank you so much damn it,silly mistake. Thanks man it worked
Topic archived. No new replies allowed.