Linked Lists

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.

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
#include <iostream>
#include <string>

using namespace 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?
no. it should just be while( current != 0)...
but then you have to change line 30 to current = root->next; (or fix the first part of the code)
Topic archived. No new replies allowed.