Ignoring all the other errors that algorism pointed out, if you look carefully you should notice that you handled the 4th node differently from the others. That part of the listing says:
Code:
n = new node;
t = t -> next;
n -> data = 4;
t -> next = n;
n -> next = null;
Unfortunately, the order that you wrote this in matters. You set t to t->next on the first highlighted line, which is a pointer that you cannot dereference; it doesn't point to a valid address, like that of another node. When you dereference it anyway in the second highlighted line, you risk a segfault. This would have never attached node 4 to node 3, just because this section of the code is different from the others. You did it right the first three times.
This kind of mistake is why loops are our friends.
Fixing other errors, a correct listing looks like this:
Code:
C:\Users\jk\Desktop>g++ foo.cpp
C:\Users\jk\Desktop>more foo.cpp
#include <iostream>
#include <cstddef>
using std::cout;
using std::cin;
using std::endl;
struct node{
int data;
node *next;
};
int main()
{
node *n; // new
node *t; // temp
node *h; // head
n = new node;
n -> data = 1;
t = n;
h = n;
n = new node;
n -> data = 2;
t -> next = n; // t is still associated with node 1. t make node 1 point to node 2.
t = t -> next; // could have said " t = n; " Now, t points to node 2.
n = new node;
n -> data = 3;
t -> next = n;
t = t -> next;
n = new node;
n -> data = 4;
t -> next = n;
n -> next = 0;
n = h;
if ( n != 0 )
{
while ( n -> next != 0 )
{
cout<< "test" << endl;
cout<< n->data << endl;
n = n->next;
}
}
//cout << "test\n" << n->data << endl;
}
C:\Users\jk\Desktop>a.exe
test
1
test
2
test
3
Works as expected. Note that the main difference is that setting t to t->next is not performed; though you can, as in the other sections, if the list is meant to be larger.
Note that the design of the loop purposefully leaves off the end node of a list because the next link is a null pointer. I don't know if that's what's being taught now in schools, but it's an important caveat.