Thread: Linked list printing out backwards

  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
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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-11-2010, 12:21 AM
  2. trouble printing linked list
    By deathrattle in forum C Programming
    Replies: 3
    Last Post: 12-02-2008, 06:29 PM
  3. trouble printing linked list
    By deathrattle in forum C Programming
    Replies: 3
    Last Post: 12-02-2008, 05:33 PM
  4. Printing a linked list
    By Jslam9 in forum C++ Programming
    Replies: 5
    Last Post: 12-14-2002, 06: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