Linked list printing out backwards

This is a discussion on Linked list printing out backwards within the C++ Programming forums, part of the General Programming Boards category; I am having problems with adding new items into a linked list. Here is my add function for the linked ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    45

    Linked list printing out backwards

    I am having problems with adding new items into a linked list.

    Here is my add function for the linked list:
    Code:
    void List::addNode(const Product & info)
    {
    	NodeType* ptr = new NodeType;
    	ptr->data = info;
    	ptr->next = head;
    	head = ptr;
    }
    When I test the program and enter in the input such as,
    10 20 30 40 50
    60 70 80 90 100

    And then tell it to output the result back to me it will output this answer:
    60 70 80 90 100
    10 20 30 40 50

    Why is it doing this? How do I make it so that it will output the answer exactly in the same order as I entered it into the system?

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,622
    Every time you do

    ptr->next = head;

    you put ptr in front of head. It sounds like you want to add to the end of the list instead.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    45
    Thank you for your input. Is there a method to insert it at the end of the list without using a tail?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,310
    Quote Originally Posted by chickenlittle
    Is there a method to insert it at the end of the list without using a tail?
    Yes, by traversing the entire linked list.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Insert as you do, but output it in reverse using recursion?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 12-10-2010, 11:21 PM
  2. trouble printing linked list
    By deathrattle in forum C Programming
    Replies: 3
    Last Post: 12-02-2008, 05:29 PM
  3. trouble printing linked list
    By deathrattle in forum C Programming
    Replies: 3
    Last Post: 12-02-2008, 04:33 PM
  4. Printing a linked list
    By Jslam9 in forum C++ Programming
    Replies: 5
    Last Post: 12-14-2002, 05:08 PM
  5. Problems printing a linked list.
    By Ed_Severson in forum C Programming
    Replies: 4
    Last Post: 05-03-2002, 10:31 PM

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