I've just finished reading up on linked lists and pointers and tried to make a simple linked list on my own, except it's not working. I tried debugging myself and I don't know where I went wrong, though I'm sure there's a lot of it that's wrong.
#include <iostream>
#include <string>
usingnamespace std;
struct Node {
int number;
Node *next;
};
int main(){
char userchoice[2];
Node *root;
Node *current;
root = new Node;
current = root;
root->next = 0;
do{
cout << "would you like to add a number to the list?(y/n) ";
cin >> userchoice;
cout << endl;
if( userchoice[0] == 'y' ){
current->next = new Node;
current = current->next;
cout << "what is the number you would wish to add? ";
cin >> current->number;
cout << endl;
}
}while ( userchoice[0] != 'n' );
current = root;
cout << "the numbers in your list are: ";
if(current != 0)
while (current->next != 0)
cout << current->number;
return 0;
}
Actually it does work (not flawlessly though: root is never assigned a value). The part which doesn't work is the output. It never goes to the next node. Make it
1 2 3 4
while (current->next != 0){
cout << current->number;
current = current->next;
}
you're right! i forgot to make current traverse the rest of the list. current isn't reading the last node though, so should i write a condition if it's at the end of the list or should i insert a sentinel node at the end of the list?