get element at special index

This commit is contained in:
shellhub 2020-09-22 11:58:41 +08:00
parent cc0e3510e2
commit e003f9a2de

View File

@ -211,6 +211,21 @@ public class SinglyLinkedList {
return false;
}
/**
* Return element at special index.
*
* @param index given index of element
* @return element at special index.
*/
public int getNth(int index) {
checkBounds(index, 0, size - 1);
Node cur = head;
for (int i = 0; i < index; ++i) {
cur = cur.next;
}
return cur.value;
}
@Override
public String toString() {
@ -251,6 +266,11 @@ public class SinglyLinkedList {
&& list.search(1)
&& !list.search(100);
/* Test get function */
assert list.getNth(0) == 10
&& list.getNth(2) == 5
&& list.getNth(4) == 1;
/* Test delete function */
list.deleteHead();
list.deleteNth(1);