Question: public class RemoveLinkedList { private static LinearNode head; public static void main(String[] args) { // create a linked list that holds 1, 2, ...,5 //

public class RemoveLinkedList {

private static LinearNode head;

public static void main(String[] args) {

// create a linked list that holds 1, 2, ...,5 // by starting at 5 and adding each node at head of list

head = null; // create empty linked list LinearNode intNode;

for (int i = 5; i >= 1; i--) { // create a new node for i intNode = new LinearNode(new Integer(i)); // add it at the head of the linked list intNode.setNext(head); head = intNode; }

printElements(); // remove the node storing the value 5 from the list remove(3); printElements(); }

// This method removes from the linked list pointed by head the node // storing the value specified by the second parameter private static void remove(int value) { LinearNode current = head, previous = null;

// Find the node storing value while (current != null) { if (current.getElement().intValue() == value) { // node storing value was found current = null; // Node deleted break; // Exit loop } else { previous = current; current = current.getNext(); } }

}

// Prints the values stored in the list pointed by head private static void printElements() { System.out.print("List of elements: "); LinearNode current = head; while (current != null) { System.out.print(current.getElement()); current = current.getNext(); if (current != null) System.out.print(", "); } System.out.println(""); } }

------------------------------------------

public class LinearNode { private LinearNode next; private E element; /** * Creates an empty node. */ public LinearNode() { next = null; element = null; } /** * Creates a node storing the specified element. * * @param elem the element to be stored within the new node */ public LinearNode (E elem) { next = null; element = elem; } /** * Returns the node that follows this one. * * @return the node that follows the current one */ public LinearNode getNext() { return next; } /** * Sets the node that follows this one. * * @param node the node to be set to follow the current one */ public void setNext (LinearNode node) { next = node; } /** * Returns the element stored in this node. * * @return the element stored in this node */ public E getElement() { return element; } /** * Sets the element stored in this node. * * @param elem the element to be stored in this node */ public void setElement (E elem) { element = elem; } } --------Fix the program and run it again to verify that the node storing the value 3 was removed.-------

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!