Thread: deleting from a linked list if there are just 2 nodes

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    4

    deleting from a linked list if there are just 2 nodes

    i'm having some trouble with a function i am trying to write. i cannot delete the second node from a DOUBLY linkedlist if there are just two nodes. here is a snippet of code within my function but i keep getting a segmentation fault, am i doing something wrong because if i comment this part of my code out it works fine:

    Code:
    Node<T> *secondNode = first->next;
    if(secondNode->next==NULL)	//check if there is just 2 nodes.
    {
    	first->next = secondNode->next;
    	delete secondNode;
    }
    Last edited by Nooby; 04-10-2010 at 10:59 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The only special node is the first one, as you also need to update the head pointer as well.

    For every other node, the logic should be the same.
    previousNode->next = nodeToBeDeleted->Next; // LL skips the node to be deleted
    delete nodeToBeDeleted;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I'm thinking in a doubly linked list you would normally have to reset a backward link from node 3 back to node 1, n'est ce pas?

    As to the OP, I hope you are first checking that there is only 1 node (as referencing secondNode->next will fail badly if secondNode doesn't exist). Otherwise, presumably either your list isn't quite being built correctly, or other operations are leaving your list in an inconsistent state.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem using strcmp and strlen in a Linked List
    By matrixx333 in forum C Programming
    Replies: 4
    Last Post: 11-23-2009, 04:13 AM
  2. deleting a node in linked list
    By BoneXXX in forum C Programming
    Replies: 18
    Last Post: 12-17-2007, 12:30 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. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM