linked list Remove a node

This is a discussion on linked list Remove a node within the C++ Programming forums, part of the General Programming Boards category; Does this seem right? I am removing an integer node from the linked list. Code: LNode* RemoveItem(LNode *headPtr, int targetItem) ...

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    3

    linked list Remove a node

    Does this seem right? I am removing an integer node from the linked list.

    Code:
    LNode*  RemoveItem(LNode  *headPtr, int  targetItem)
    {
        struct LNode *trailPtr;
        for (headPtr = LNode; headPtr != NULL; headPtr = headPtr ->next)
            {
            if (headPtr ->value == targetItem)
                {
                if (headPtr == LNode)
                    {
                    LNode = headPtr ->next;
                    }
                else
                    {
                    trailPtr ->next = headPtr ->next;
                    break;
                    }
                trailPtr = headPtr;
                }
            }
    return headPtr;
    }  // end of "RemoveItem"

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Code:
    headPtr = LNode
    What does this line do?You assign the headPtr in your type of struct?
    It is like doing with an integer for example
    Code:
    int a;
    int * b
    b = int; /* Not what you want */
    When we handle lists we use as a stop condition(in order to traverse through the list)
    Code:
    while(listPointer != NULL)
    {
              /* Your logic here */
              listPointer = listPointer->next; /* Go to the next node */
    }
    The code above assumes that your struct has a member that is a pointer to list, and it called next, which is pretty usual in linked lists.

    PS - i suspect this is C code, not C++
    The last node of the list has no next node, so it's member next should be set to NULL.
    If the list is empty ,then we set the pointer of the list to NULL.

    After you understand what i said ,pick up a pencil and a paper and draw a list with four nodes.Try to remove the 2nd node of it.See what you do in paper with your pointers and do it in your code.Then try to do the same for the first node and again watch what you did in paper.Same story for last node.

    Try your code, and if needed post back

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 18
    Last Post: 11-27-2011, 04:01 AM
  2. Replies: 0
    Last Post: 09-16-2008, 06:04 AM
  3. Linked List remove node issue
    By prihod in forum C Programming
    Replies: 1
    Last Post: 04-19-2008, 10:54 AM
  4. traversing a linked list with a node and list class
    By brianptodd in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2003, 12:57 PM
  5. Replies: 5
    Last Post: 10-04-2001, 04:42 PM

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