Thread: Adding nodes into linked list

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Kansas City
    Posts
    76

    Adding nodes into linked list

    I am having trouble insearting values into a linked list, program keeps crashing. What is wrong with this function?

    Code:
    void add_node()
    {  
         Node *temp, *temp2;   
       
         cout << "Please enter a number";
         cin >> temp -> item;
         temp -> next = NULL; 
    
         if (head == NULL) 
                 head = temp;         
              else
         { 
             temp2 = head; 
             while (temp2 -> next != NULL) 
                 temp2 = temp2 -> next; 
             temp2 -> next = temp;    
      }
    }
    node looks like this:
    Code:
    struct Node
    {
           int item;   
           Node *next; 
    };

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You should allocate a new node, because - as it is - you're using an unintialized pointer (temp)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  2. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  3. Adding directory/file names to a linked list
    By thoseion in forum C Programming
    Replies: 13
    Last Post: 12-08-2006, 01:13 PM
  4. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  5. How to use Linked List?
    By MKashlev in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 07:11 AM