CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2006
    Location
    beyond the pillars of hercules
    Posts
    295

    [RESOLVED] Linked List - Addng entry at the end

    i have a Node and i want to add a new entry at the end
    the first entry is added correctly on head but the next entry is not added at all

    Code:
    struct Node
    {
    	FlightRec entry;
    	Node *next;
    };
    class List 
    {
    public:
    	void ReadFlight();
    	void AddFlight(FlightRec iInput);
    
    private:
    	Node *head;
    };
    
    
    void List::AddFlight(FlightRec iInput)
    {
    	Node* New_Node = new Node;
    	New_Node->entry = iInput;
    	New_Node->next = NULL;
    
    	if (head == NULL)
    	{
    		head = New_Node;
    		head->next = NULL;
    	}
    	else
    	{
    		Node* previous = head, *current = head->next ;
    
    		while(current != NULL)
    		{
    			previous = current;
    			current = current->next;
    		}
    
    current = New_Node;
    // head->next = New_Node;
    current->next = NULL;
    
    bool breakpoint = false;
    	}
    
    }
    when i use head->next = New_Node; it adds the new entry but not if i use the current pointer
    any ideas why??

    thanks

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Linked List - Addng entry at the end

    After the while loop, current is guaranteed to be NULL. (Check the while condition, this should be obvious). Therefore, setting current to New_Node is not useful.

    By contrast, previous should still be pointing to the last node of the list so far. Does that give you a hint as to what you need to be doing differently?

  3. #3
    Join Date
    May 2006
    Location
    beyond the pillars of hercules
    Posts
    295

    Re: Linked List - Addng entry at the end

    thanks for the help Lindley and itsmeandnobodyelse, i should have been using 'previous' instead of 'current'

  4. #4
    Join Date
    Oct 2009
    Posts
    577

    Smile Re: Linked List - Addng entry at the end

    To add to above comment:

    You have a commented statement 'head->next = New_Node;'

    That statement obviously would do the 'linking' from first node to the second one which therefore is too special and probably is commented because of that.

    Can you find the statement which would link the new node to the 'last' node not NULL?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured