# Write a function to delete a Linked List

Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to access next of the current pointer if current pointer is deleted.

In Java, automatic garbage collection happens, so deleting a linked list is easy. We just need to change head to null.

Implementation:

## C/C++

```// C program to delete a linked list
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

struct Node
{
int data;
struct Node* next;
};

/* Function to delete the entire linked list */
{
struct Node* next;

while (current != NULL)
{
next = current->next;
free(current);
current = next;
}

in the caller. */
}

/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data  */
new_node->data  = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Drier program to test count function*/
int main()
{

/* Use push() to construct below list
1->12->1->4->1  */

}
```

## Java

```// Java program to delete a linked list
{

class Node
{
int data;
Node next;
Node(int d) { data = d; next = null; }
}

/* Function deletes the entire linked list */
void deleteList()
{
}

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

public static void main(String [] args)
{
/* Use push() to construct below list
1->12->1->4->1  */

llist.push(1);
llist.push(4);
llist.push(1);
llist.push(12);
llist.push(1);

System.out.println("Deleting the list");
llist.deleteList();

}
}
// This code is contributed by Rajat Mishra
```

Output:
``` Deleting linked list

Time Complexity: O(n)
Auxiliary Space: O(1)

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.4 Average Difficulty : 1.4/5.0
Based on 173 vote(s)