Adding nodes into linked list

This is a discussion on Adding nodes into linked list within the C++ Programming forums, part of the General Programming Boards category; I am having trouble insearting values into a linked list, program keeps crashing. What is wrong with this function? Code: ...

  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-28-2008, 12:24 AM
  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, 11:01 AM
  5. How to use Linked List?
    By MKashlev in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 08:11 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21