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);


		return 0;


	void output(NodePtr head)
		NodePtr temp = head;
			cout<<"end of list"<<endl;

			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? 
9 Years
Discussion Span
Last Post by Ancient Dragon

The function beginning at line 52 inserts a new node at the head of the linked list. It does this by first setting the new nodes's link pointer to the current head, then changing the current head to be the new node. The function looks like it will work correctly.

>>And i think my output function is not right
You are correct -- that function is not correct because it needs a loop to iterate through the linked list and print them one at a time

while( temp != NULL)
    // print the node's data is not shown

   // advance to the next node
   temp = temp->Link;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.