From 14d67ffdf45745b69a05dd6cc356038e3df1745e Mon Sep 17 00:00:00 2001 From: shellhub Date: Tue, 15 Oct 2019 22:18:12 +0800 Subject: [PATCH] clear list --- DataStructures/Lists/SinglyLinkedList.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 8747aebb..1b442e52 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -106,6 +106,25 @@ public class SinglyLinkedList { } } + /** + * clear all nodes in list + */ + public void clear() { + if (size == 0) { + return; + } + Node prev = head.next; + Node cur = prev.next; + while (cur != null) { + prev = null; // clear to let GC do its work + prev = cur; + cur = cur.next; + } + prev = null; + head.next = null; + size = 0; + } + /** * Checks if the list is empty *