Thread: removing nodes from linked list

  1. #1
    Registered User brianptodd's Avatar
    Join Date
    Oct 2002
    Posts
    66

    removing nodes from linked list

    How do I remove an interior node from a singly linked list? I am using a node class with a double data member and a list class.
    "In theory, there is no difference between theory and practice. But, in practice, there is."
    - Jan L.A. van de Snepscheut

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    I think this should work.
    Code:
    //If s->Next is the Node that you want to delete then do this
    Node* temp;
    temp = s->Next;
    s->Next = s->Next->Next;
    delete temp;

  3. #3
    Registered User brianptodd's Avatar
    Join Date
    Oct 2002
    Posts
    66

    ok

    but what if the node you want to remove is s? how do i access the previous->next that points to s, and switch that to s->next?
    "In theory, there is no difference between theory and practice. But, in practice, there is."
    - Jan L.A. van de Snepscheut

  4. #4
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    What you do is iterate through the list until s->Next is the Node that you wanna delete, that's all.

    Note: This will only work if you have a head node that you don't use.

    //Edit: Here's an example
    Code:
    while( s->Next != NULL )
    {
         if( s->Next->data == valueToDelete )
         {
              Node* temp;
              temp = s->Next;
              s->Next = s->Next->Next;
              delete temp;
              break;
         }
         s = s->Next;  //Forgot this
    }
    Last edited by The Dog; 10-25-2003 at 02:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  2. singly linked to doubly linked
    By jsbeckton in forum C Programming
    Replies: 10
    Last Post: 11-06-2005, 07:47 PM
  3. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM
  4. List class
    By SilasP in forum C++ Programming
    Replies: 0
    Last Post: 02-10-2002, 05:20 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM