1 2 3 4 5 6 7 8 9 10 11 12 13
|
do
{
if (data == 0)
{
cout << "NULL" << endl;
return 0;
}
if (head == NULL)
{
head = newnode;
head->m_next = NULL;
}
|
I don't think this belongs in the loop, because this part of the logic only happens once, at the beginning.
1 2 3 4 5 6
|
current = head;
while (current != NULL)
{
current = current->m_next;
}
current = newnode;
|
This looks odd, so it probably isn't doing what you want to.
You assign head to current, but then you keep re-assigning current until current is NULL. Then you assign current to be newnode. In other words, your lines 42 to 26 don't do anything useful, because you are re-assigning current right afterward.
You also never allocate any more memory beyond the first node -- you need to call
new every time you want to allocate a new node.
________________________________________________________
This probably could be beautified a bit further, but this should fix your problems:
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
|
#include <iostream>
using namespace std;
class Node
{
public:
int m_data;
Node *m_next;
};
Node* getListFromUser()
{
int data = 0; // It's good to initialize things so you know what to expect
Node *head = NULL; // the newnode variable is redundant and just makes things more convoluted
Node *current = NULL;
cout << "Enter numbers, press 0 to stop: ";
cin >> data;
if (data == 0)
{
cout << "NULL" << endl;
return NULL;
}
// At this point, we know we should have at least 1 valid node in the linked list
head = new Node;
head->m_data = data;
head->m_next = NULL;
current = head;
cin >> data;
while (data != 0)
{
current->m_next = new Node; // allocate the next node
current = current->m_next;
current->m_data = data;
current->m_next = NULL;
cin >> data;
}
return head;
}
int main()
{
Node *head = getListFromUser();
Node *curr = head;
while (curr != NULL)
{
cout << "Next #: " << curr->m_data << endl;
Node *next = curr->m_next; // copy pointer to next before we delete current
delete curr;
curr = next;
}
return 0;
}
|