Insert Function For Linked Lists?

This is a discussion on Insert Function For Linked Lists? within the C++ Programming forums, part of the General Programming Boards category; Hi, My problem is when I insert stuff into the linked list and then print it out the output I ...

  1. #1
    Registered User Daniel's Avatar
    Join Date
    Jan 2003
    Posts
    47

    Insert Function For Linked Lists?

    Hi,

    My problem is when I insert stuff into the linked list and then print it out the output I recieve is backwards.
    Ex: input: 12345
    output: 54321
    So is there a way I can change my insertLL to correct this problem?
    void insertLL(node *& L, node * temp)
    {
    temp->next=L;
    L=temp;
    }

    Thank you in advance

  2. #2
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>My problem is when I insert stuff into the linked list and then print it out the output I recieve is backwards.
    What you're doing is adding at the front of the list, what you want is to add at the end. The easiest way is to maintain a tail node
    Code:
    #include <iostream>
    
    using namespace std;
    
    struct node {
      int item;
      node *next;
    
      node(int init, node *link): item(init), next(link){}
    };
    
    int main()
    {
      node *head, *tail;
      node *np, *forward;
    
      head = new node(0, 0); // Dummy head
      tail = head;
    
      for (int i = 1; i < 6; i++)
      {
        tail->next = new node(i, 0);
        tail = tail->next;
      }
    
      cout<<"Head -- "<< head->item <<endl;
      cout<<"Tail -- "<< tail->item <<endl;
    
      for (np = head->next; np != 0; np = forward)
      {
        forward = np->next;
        cout<< np->item <<flush;
        delete np;
      }
    }
    *Cela*

  3. #3
    Peace
    Join Date
    Aug 2001
    Posts
    1,510
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  4. need help understanding Linked lists
    By Brain Cell in forum C Programming
    Replies: 6
    Last Post: 07-16-2004, 01:29 PM
  5. Replies: 4
    Last Post: 11-23-2003, 06:15 AM

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