Skip to content

Updated SinglyLinkedList #1477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 22, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
get element at special index
  • Loading branch information
realDuYuanChao committed Sep 22, 2020
commit e003f9a2debe1889c5aad8e4ed7b9a7536ec191b
20 changes: 20 additions & 0 deletions DataStructures/Lists/SinglyLinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,21 @@ public boolean search(int key) {
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() {
Expand Down Expand Up @@ -251,6 +266,11 @@ public static void main(String[] arg) {
&& 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);
Expand Down