Why don't i need to print the last element |
Because the last element contains garbage. Consider the case where you input one element:
- line 21 creates the first element.
- line 28 puts the data in the first element
- line 29 creates a second element.
By the way, that second element is uninitialized.
To start, create a constructor for node:
1 2 3 4
|
node::node(int i) :
data(i),
next(NULL)
{;}
|
Next you should create exactly as many elements as you need in the list. That means initializing root to NULL and creating the node after you read the value for it.
To create the list, you need to handle the case where the list is empty:
1 2 3 4 5 6 7 8 9 10 11
|
node *root = NULL;
node *last = NULL; // points to last item in list, or NULL
while(scanf("%d", &i) != EOF){
node *n = new node(i)
if (last) {
last->next = n; // list isn't empty. Add n to the end.
} else {
root = n; // list is empty, make n the root
}
last = n;
}
|
Since this isn't he beginner forum, I'll point out that you can simplify the code by using a pointer to the current pointer instead of a "last" pointer:
1 2 3 4 5 6 7
|
node *root = NULL;
node **pp = &root; // Points to root or the last node's "next" pointer.
while(scanf("%d", &i) != EOF){
node *n = new node(i);
*pp = n;
pp = &n->next;
}
|
Finally, you'll have to change
count()
and the loop at lines 37-40 to deal with the fact that the list contains exactly the right number of items.
Speaking of
count()
, line 9 doesn't do anything. Line 8 guarantees that n->next is not NULL inside the loop.