Skip to content

Commit 14d67ff

Browse files
clear list
1 parent eec7f3e commit 14d67ff

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

DataStructures/Lists/SinglyLinkedList.java

+19
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,25 @@ public void deleteNth(int position) {
106106
}
107107
}
108108

109+
/**
110+
* clear all nodes in list
111+
*/
112+
public void clear() {
113+
if (size == 0) {
114+
return;
115+
}
116+
Node prev = head.next;
117+
Node cur = prev.next;
118+
while (cur != null) {
119+
prev = null; // clear to let GC do its work
120+
prev = cur;
121+
cur = cur.next;
122+
}
123+
prev = null;
124+
head.next = null;
125+
size = 0;
126+
}
127+
109128
/**
110129
* Checks if the list is empty
111130
*

0 commit comments

Comments
 (0)