Contenu du cours
Java Data Structures
Java Data Structures
2. Additional Data Structures
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 thedisplay()
method. However, instead of printing the elements to the screen, increment the variable you created; - In the
delete()
method, pass theindex
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 settinghead = 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 indisplay()
, but instead of printing values, increment a counter; - Mind the edge cases – in the
delete()
method, always check ifindex == 0
to properly updatehead
, 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.
Tout était clair ?
Merci pour vos commentaires !
Section 1. Chapitre 7