Thread: How to add element to the end of a linked list?

  1. #1
    Yin
    Guest

    How to add element to the end of a linked list?

    I know that it is more common to add new element at the head of the linked list. However, can we add it at the tail?

    First we should make the new element point to null. Second we should cut the linkage between the last bond and make the originally-last-element point to the new element.

    I do not know how to do the second step.

    Can anyone help? Thanks~

  2. #2
    Registered User DeadArchDown's Avatar
    Join Date
    Apr 2002
    Posts
    28
    Code:
    currPtr = head;
    
    while( currPtr->nextNode != NULL)
         currPtr = currPtr->nextNode;
    
    currPtr->nextNode = new node;
    
    currPtr->nextNode->nextNode=NULL;
    Thats unchecked, but should be a working method. Find the end of the list, attach it to a new node, and then point that node to NULL.
    -------------------
    "Exception"

  3. #3
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    Seems correct to me.

  4. #4
    Unregistered
    Guest
    Ok the only reason I know this is because Im working with a linked list as we speak. Here's what I did:

    I have a class called Node where i declared a pointer of type Node called *nextNode. I set that equal to null. In a separate class called List, I declared three pointers of type Node called *startNode, *currNode, *endNode. I have a function in my List class called insertAtBack() which does this:

    Node *newCheckNode=new Node(x,dt,t,amt);
    assert(newCheckNode!=0);
    if(endNode){
    endNode->nextNode=newCheckNode;
    endNode=newCheckNode;
    }
    else
    startNode=endNode=newCheckNode;

    So basically Im creating a new pointer of type Node and I am assigning a new chunk of memory to it. Next, I say if there is a value in my endNode, then endNode's nextNode will point to newCheckNode and endNode will equal newCheckNode.
    Otherwise, it is pretty obvious what it does.

    Good Luck!
    Shishir

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  2. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  3. how to add a note to the begining of linked list
    By merixa in forum C++ Programming
    Replies: 8
    Last Post: 10-24-2005, 02:10 AM
  4. How to use Linked List?
    By MKashlev in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 07:11 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM