# How to Clear Linked List in Java?

Linked lists are a fundamental data structure in Java, consisting of nodes that are connected through pointers. Each node contains data and a reference to the next node in the list. While linked lists offer flexibility in terms of dynamic memory allocation, it is crucial to clear them properly to avoid memory leaks and ensure efficient memory management.

We will dive into three different approaches to clear a linked list in Java: the traditional, recursive, and iterative approach. We will also compare their performance.

Before we delve into the clearing techniques, let's quickly recap the basics of linked lists. In a singly linked list, each node contains two components: the data and the next pointer. The first node is called the head, and the last node points to null.

The traditional approach to clearing a linked list involves traversing the list and removing each node one by one. We start from the head and iterate through the list until we reach the end, freeing the memory occupied by each node along the way.

## Using Recursive Approach

Another way to clear a linked list is through a recursive approach. In this method, we define a recursive function that traverses the list and removes each node. We call this function recursively until we reach the end of the list.

Output:

```Original List:
1 2 3
List after clearing:
```

## Using Iterative Approach

The iterative approach to clearing a linked list is similar to the traditional approach but uses a loop instead of recursion. We start from the head and continue until we reach the end of the list, freeing the memory occupied by each node.

Output:

```Linked List elements before clearing:
1 2 3 4 5
```

Complexity

Now that we have explored the three different approaches to clearing a linked list in Java. Let's compare their performance and see which is much better.

The traditional approach and the iterative approach have similar time complexities of O(n), where n is the number of nodes in the linked list. However, the recursive approach may have a higher time complexity due to the overhead of function calls.

In terms of space complexity, all three approaches have a constant space complexity of O(1) since we are only using a few extra variables to traverse and clear the list.

## Conclusion

Clearing a linked list in Java is an essential task to ensure proper memory management and prevent memory leaks. We have explored three different approaches: the traditional approach, the recursive approach, and the iterative approach.

While all three methods effectively clear a linked list, it is crucial to consider the trade-offs between time complexity and code readability. The traditional and iterative approaches are generally preferred due to their simplicity and similar performance.