Confused results from Linked List
Please ignore any memory leaks here, I have removed the clean up code to reduce space.
This is no doubt a very simple mistake, however I can't see it. If I use a pointer within the struct NODE to hold the integer data, The last number that I entered is all that is output.. however if I change the variable over to an auto variable the list works.
Code:
#include <iostream>
using namespace std;
typedef struct Node
{
int *data;
Node *next;
}NODE;
// Function prototypes
void insert(int *);
void output(void);
// The list
NODE *list = NULL;
int main(void)
{
int num;
cout << "Enter a number: ";
cin >> num;
while (num != 999)
{
insert(&num);
cout << "Enter a number: ";
cin >> num;
}
output();
return 0;
}
void insert(int *data)
{
NODE *temp = new NODE;
temp->data = new int;
temp->next = list;
temp->data = data;
list = temp;
}
void output(void)
{
NODE *current;
current = list;
while (current != NULL)
{
cout << "Number: " << *current->data << endl;
current = current->next;
}
}