Skip to content

Commit 95484f8

Browse files
update SinglyLinkedList (TheAlgorithms#2058)
1 parent c85223b commit 95484f8

File tree

1 file changed

+6
-15
lines changed

1 file changed

+6
-15
lines changed

DataStructures/Lists/SinglyLinkedList.java

+6-15
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
11
package DataStructures.Lists;
22

3-
/**
4-
* This class implements a SinglyLinked List. This is done using SinglyLinkedList class and a
5-
* LinkForLinkedList Class.
6-
*
7-
* <p>A linked list is similar to an array, it hold values. However, links in a linked list do not
8-
* have indexes. With a linked list you do not need to predetermine it's size as it grows and
9-
* shrinks as it is edited. This is an example of a singly linked list. Elements can only be
10-
* added/removed at the head/front of the list.
11-
*/
3+
import java.util.StringJoiner;
4+
5+
/** https://en.wikipedia.org/wiki/Linked_list */
126
public class SinglyLinkedList {
137
/** Head refer to the front of the list */
148
private Node head;
@@ -213,16 +207,13 @@ public int getNth(int index) {
213207

214208
@Override
215209
public String toString() {
216-
if (size == 0) {
217-
return "";
218-
}
219-
StringBuilder builder = new StringBuilder();
210+
StringJoiner joiner = new StringJoiner("->");
220211
Node cur = head;
221212
while (cur != null) {
222-
builder.append(cur.value).append("->");
213+
joiner.add(cur.value + "");
223214
cur = cur.next;
224215
}
225-
return builder.replace(builder.length() - 2, builder.length(), "").toString();
216+
return joiner.toString();
226217
}
227218

228219
/** Driver Code */

0 commit comments

Comments
 (0)