0

I'm having issues as to how to modify the pointers, using the previous and next instance variables of an object of class type Element. The doubly linked list is filled with Element objects with a lastName, firstName, phoneNumber, previous, and next instance variables. The removeElement method accepts the lastName as a parameter and finds an element with that exact String and then deletes it from the list. However, when modifying the pointers that are supposed to delete the Element from the list I came across an exception. Specifically, at this block of code:

previousNode.nextElement = currentNode.nextElement;
currentNode = currentNode.nextElement;
currentNode.previousElement = previousNode;

It throws an exception after deleting a node in the middle and then trying to delete the node at the end of the list. So I'm definitely not properly modifying the instance variables to link the elements previous and next to the deleted element. How could I set the pointers of both the previous and next elements towards each other, while following the constraints of the program?

Here's the code in case it will contribute to an answer:

    package linkedlist;

import java.util.Scanner;

class Element
{
   String      firstName;        
   String      lastName;
   long        phoneNumber;
   Element     nextElement;      // Pointer to next element in the list
   Element     previousElement;  // Pointer to the last element in the list

   // Default Constructor
   public Element()
   {
      this.firstName = null;
      this.lastName = null;
      this.phoneNumber = 0;
      this.nextElement = null;
      this.previousElement = null;
   }

   // Constructor providing first and last name
   public Element( String first, String last, long number )
   {
      this.firstName = first;
      this.lastName = last;
      this.phoneNumber = number;
      this.nextElement = null;
      this.previousElement = null;
   }

   public String toString()
   {
      return( this.firstName + " "  + this.lastName + " Cell: " + this.phoneNumber);
   }
}


class ElementList
{
   Element       firstNode;
   Element       lastNode;
   public ElementList()
   {
      this.firstNode = null;
      this.lastNode = null;
   }

   public void addElement( String first, String last, long number )
   {
      Element    newNode;
      newNode = new Element( first, last, number );

      if ( this.firstNode == null)
      {
         this.firstNode = newNode;
         this.lastNode = newNode;
      }
      else
      {
         this.lastNode.nextElement = newNode;
         newNode.previousElement = this.lastNode;
         this.lastNode = newNode;
      }
   }

   public void deleteElement( String last )
   {
      Element     currentNode, previousNode = null;

      currentNode = this.firstNode; //Temporarily assigns it 
      while( currentNode != null ) //Checks if there's items.
      {
         if ( currentNode.lastName.equalsIgnoreCase( last ) == true ) //Checks the last name
         {
            // We want to delete this node
            if ( this.firstNode == currentNode )
            {
               // Delete first Node, point first node to next element
               this.firstNode = this.firstNode.nextElement;
            }
            else
            {
               /* Point the next element of the previous element to the next element
                  of the current element, thus deleting the current element
               */
               previousNode.nextElement = currentNode.nextElement;
               currentNode = currentNode.nextElement;
               currentNode.previousElement = previousNode;
            }
            break;
         }
         else
         {
            // Move to next element
            previousNode = currentNode;    // Save current node to previous
            currentNode = currentNode.nextElement;  // Move to next node
         }
      }
   }

   public void printElements()
   {
      Element     currentNode;

      System.out.println( "\nList of Elements\n================");
      if ( this.firstNode == null )
      {
         System.out.println( "No Elements in List\n" );
      }
      else
      {
         currentNode = this.firstNode;    // Point to first element
         while ( currentNode != null )    // Traverse entire list
         {
            System.out.println( currentNode );  // Print Element contents
            currentNode = currentNode.nextElement;  // Go to next node
         }
      }
   }
   public void printReverseElements()
   {
      Element currentNode;

      System.out.println( "\nList of Elements in Reverse\n================");
      if(this.lastNode == null)
      {
         System.out.println("No Elements in List\n");
      }
      else
      {
         currentNode = this.lastNode;
         while (currentNode != null)
         {
            System.out.println(currentNode);
            currentNode = currentNode.previousElement;
         }
      }
   }
}


public class LinkedList 
{
   public static void main(String[] args) 
   {
      Scanner     keyboard = new Scanner( System.in );
      ElementList list;
      String      first, last;
      double number;

      list = new ElementList();        // Instantiate the ElementList

      System.out.print( "Enter Last Name, <CR> to Exit   : " );
      last = keyboard.nextLine();             // Read last Name
      while ( last.length() != 0 )
      {
         System.out.print( "Enter First Name                : " );
         first = keyboard.nextLine();         // Read first Name
         System.out.print("Enter Phone Number              : ");
         number = keyboard.nextLong();
         list.addElement(first, last, (long) number); 
         list.printElements();// Add Element to ElementList
         if ( keyboard.hasNextLine())
         {
             keyboard.nextLine();
         }
         System.out.print( "Enter Last Name, <CR> to Exit   : " );
         last = keyboard.nextLine();
      }
      list.printElements();
      list.printReverseElements();
      System.out.print( "Enter Last Name to Delete or <CR> to Exit: " );
      last = keyboard.nextLine();
      while ( last.length() != 0 )
      {
         list.deleteElement( last );
         list.printElements();
         System.out.print( "Enter Last Name to Delete or <CR> to Exit: " );
         last = keyboard.nextLine();
      }
   }
}

or just the removeElement method for convenience:

       public void deleteElement( String last )
   {
      Element     currentNode, previousNode = null;

      currentNode = this.firstNode; //Temporarily assigns it 
      while( currentNode != null ) //Checks if there's items.
      {
         if ( currentNode.lastName.equalsIgnoreCase( last ) == true ) //Checks the last name
         {
            // We want to delete this node
            if ( this.firstNode == currentNode )
            {
               // Delete first Node, point first node to next element
               this.firstNode = this.firstNode.nextElement;
            }
            else
            {
               /* Point the next element of the previous element to the next element
                  of the current element, thus deleting the current element
               */
               previousNode.nextElement = currentNode.nextElement;
               currentNode = currentNode.nextElement;
               currentNode.previousElement = previousNode;
            }
            break;
         }
         else
         {
            // Move to next element
            previousNode = currentNode;    // Save current node to previous
            currentNode = currentNode.nextElement;  // Move to next node
         }
      }
   }

The assignment as well (skip to task 5): https://drive.google.com/file/d/1POEAsdNrB3wJPI0ddsbJp2HnUay5pgei/view?usp=sharing

Any answer will be appreciated!

1 Answer 1

0

The problem occurs when you are removing last element from the list.

Update firstNode, lastNode objects as follows:

public void deleteElement(String last) {
    Element currentNode, previousNode = null;
    currentNode = this.firstNode;

    while (currentNode != null) {
        if (currentNode.lastName.equalsIgnoreCase(last) == true) {
            if (this.firstNode == currentNode) {
                this.firstNode = this.firstNode.nextElement;
                if (this.firstNode != null) {
                    this.firstNode.previousElement = null;
                } else {
                    this.lastNode = null;
                }
            } else {
                previousNode.nextElement = currentNode.nextElement;
                if (currentNode.nextElement != null) {
                    currentNode = currentNode.nextElement;
                    currentNode.previousElement = previousNode;
                } else {
                    this.lastNode = previousNode;
                }
            }
            break;
        } else {
            previousNode = currentNode;
            currentNode = currentNode.nextElement;
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Ah! That fixed the problem! however, the strange thing about is when I need to delete the last element of the list it would prompt for me to do it twice? As in, when I prompt for the last name on the list it wouldn't remove it at first and then I would have to type the name again to have it finally removed.
You might have entered same last name multiple times while creating the list, and searching is done linearly from first element. Try with different last names, it works!
ahaha I see what I did wrong, I kept the else if statement which you removed. it works now! however, now with that problem gone also arises on the printReverse method whereas the deleted names still appear on the list. I assume that the deleteElement method isn't actually deleting the elements, however the regular print method is working just fine?
You were not updating firstNode, lastNode pointers properly. Corrected my own answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.