Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Challenge: LinkedList | Basic Data Structures
Java Data Structures
course content

Kursinhalt

Java Data Structures

Java Data Structures

1. Basic Data Structures
2. Additional Data Structures
3. Map
4. enum & Stream API

book
Challenge: LinkedList

Task

You implemented three out of four CRUD operations together. In this task, you need to implement two methods:

  • public int size();
  • public void delete(int index).

The assignment is on GitHub, so you need to implement it locally in your IDE.

You'll see the solution to this task with comments on the implementation.

A brief guide on how to complete this task:

  • I suggest starting with the size() method. First, you need to declare a variable to keep track of the number of elements in the list, and then simply return this variable from the method;
  • In the size() method, follow the same steps as in the display() method. However, instead of printing the elements to the screen, increment the variable you created;
  • In the delete() method, pass the index as a parameter. It is essential to validate the index to ensure it is within the correct range.
  • If index == 0, simply update the reference by setting head = head.next;
  • Next, perform operations with the for loop to find the desired index of the element;
  • Once the required element is found, perform the following operation:
    node.next = node.next.next;;
  • This way, you will remove the reference to the deleted element, effectively deleting it from the list.

Once you finish the task, you can run the main method, where some tests are provided for you.

Additionally, you can run the unit tests located in the test folder to validate your solution.

  • Iterate carefully – when implementing the size() method, traverse the list just like in display(), but instead of printing values, increment a counter;
  • Mind the edge cases – in the delete() method, always check if index == 0 to properly update head, and ensure the index is within bounds before proceeding;
  • Update links correctly – when deleting a node, update current.next = current.next.next to bypass the element, effectively removing it from the list.
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 7
We're sorry to hear that something went wrong. What happened?
some-alt