I followed the book to finish this 2 node linked list, and however it looks like there is only one node in it. (temp has replaced the head???? my book example coded this way which i don't fully understand) Is anything wrong in here? And i think my output function is not right... it doesn't detect the NULL,,, or if it is something wrong? please help pointing it out.
# include <iostream>
using namespace std;
struct Node
{
int data;
Node *link;
};
typedef Node* NodePtr;
void head_insert(NodePtr& head, int the_number);
void output(NodePtr head);
int main()
{
NodePtr head= new Node;
head->data =2;
head->link= NULL;
head_insert(head, 3);
output(head);
return 0;
}
void output(NodePtr head)
{
NodePtr temp = head;
if(temp->link==NULL)
{
cout<<"end of list"<<endl;
}
else
{
cout<< temp->data<<endl;
}
}
void head_insert(NodePtr& head, int the_number)
{
NodePtr temp_ptr;
temp_ptr = new Node;
temp_ptr->data= the_number;
temp_ptr->link= head;
head = temp_ptr; //does this overwrite the first node?
}