diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 668a40da..1df0b413 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -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);