I was writing my own linked list implementation as follows, when I tried to perform operation 'deleteElementFromHead' of the linkedlist, I was curious that what I did was enough or not? The method for deletion of element from head is as follows,
public void deleteAtHead()
{
Node secondNode = this.head.next;
this.head = secondNode;
count--;
}
I am in doubt that while exchanging the pointers to delete element at head, the old head element is still in the memory, and may or may not be collected by the garbage collector. Do I need to set that deleted element to null, or need to add some other piece of code in the above method to avoid memory leak.
The complete code piece for the linkedlist is as follows,
package com.nobalg.Linkedist;
public class Node implements Operations {
int data;
Node next,head,tail;
int count = 1;
public Node(int data)
{
this.data = data;
this.head=this;
this.tail = this;
}
/**********This method takes O(n) time************/
public void addNode(int nodeData)
{
Node node = new Node(nodeData);
Node temp = this;
while(temp.next!=null){
temp = temp.next;
}
temp.next = node;
count++;
}
/******This operation takes O(1) time********/
public void addAtTail(int nodeData)
{
Node node = new Node(nodeData);
tail.next = node;
tail = tail.next;
count++;
}
/********This operation takes O(1) time**************/
public void addAtHead(int nodeData)
{
Node node = new Node(nodeData);
node.next = head;
this.head = node;
count++;
}
/************This operation takes O(n) time****************/
public void addAtIndex(int index,int nodeData)
{
if(index < 0 || index >count)
{
throw new IllegalStateException();
}
Node node = new Node(nodeData);
Node tempLast = this.head;
Node tempCurrent = this.head;
int locCount = 0;
while(locCount!=index){
tempLast = tempCurrent;
tempCurrent = tempCurrent.next;
locCount++;
}
node.next = tempCurrent;
if(index == 0)this.head = node;
else tempLast.next = node;
count++;
}
/**********This operation takes O(n) time in case of singly linked list*************/
public void deleteAtTail()
{
Node temp = this.head;
Node locLastNode = null;
while(temp.next!=null)
{
locLastNode = temp;
temp = temp.next;
}
this.tail = locLastNode;
locLastNode.next = null;
count--;
}
public void deleteAtHead()
{
Node secondNode = this.head.next;
this.head = secondNode;
count--;
}
public void deleteAtIndex()
{
//implementation pending
}
public int size()
{
return count;
}
public void display()
{
Node temp = this.head;
for(int i = 0 ; i < count; i++)
{
System.out.println(temp.data);
temp = temp.next;
}
}
}