Computer Science Canada

Removing an element from a Linked List

Author:  randint [ Wed Dec 05, 2012 11:23 pm ]
Post subject:  Removing an element from a Linked List

How do you remove an element from a custom (non built-in) LinkedList?
Java:

import java.io.*;
public class Node
{
    Node next;
    String data;

    public Node (String data)
    {
        this.data = data;
    }
}

public class LinkedListExerciseSolution
{
    public static void main (String[] args) throws IOException
    {
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));

        // declare nodes and string for user input
        Node node, head;
        String userData;

        // initialise the head to null
        head = null;

        // loop to create new nodes for the linked list using user data
        do
        {
            System.out.print ("What name would you like stored? (\"quit\" to end) ");
            userData = stdin.readLine ();

            // create a new node if the user has not decided to quit
            if (!userData.equals ("quit"))
            {
                node = new Node (userData);
                node.next = head;

                // update the head to point to the new front of the list
                head = node;
            }
        }
        while (!userData.equals ("quit"))// loop continues until "quit" selected

        // print a blank line and reset pointer to start of linked list
        System.out.println();
        node = head;

        // loop through entire linked list to display its contents
        do
        {
            System.out.println (node.data);
            node = node.next;
        }
        while (node != null)// loop until the end of lists is reached
    }
}

What do I need to do in order to remove a node (as specified by the user)?

Author:  Panphobia [ Wed Dec 05, 2012 11:27 pm ]
Post subject:  RE:Removing an element from a Linked List

http://www.cs.bu.edu/teaching/cs112/spring-2000/linked-list-delete/

Author:  Tony [ Thu Dec 06, 2012 12:33 am ]
Post subject:  Re: Removing an element from a Linked List

randint @ Wed Dec 05, 2012 11:23 pm wrote:
What do I need to do in order to remove a node (as specified by the user)?

I find that drawing this out as a diagram on paper is very helpful in understanding what needs to happen. http://compsci.ca/blog/super-paper-programming/

Author:  joshm [ Thu Dec 06, 2012 8:29 am ]
Post subject:  RE:Removing an element from a Linked List

find the node before the node you want to remove, then set the next node to the node after the node you want to remove


: