Thread: Insert Function For Linked Lists?

  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

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, 07:15 AM