## Free Data Structures and Algorithms Course

### How to implement Singly LinkedList in Java ?.

Program to demonstrate implementation of Singly LinkedList in Java

```public class ListNode {

private int integerData;
private ListNode nextNode;

ListNode(int data)
{
this.integerData = data;
}

public int getIntegerData()
{
return integerData;
}

public void setIntegerData(int data)
{
this.integerData = data;
}

public ListNode getNextNode()
{
return nextNode;
}

public void setNextNode(ListNode next)
{
this.nextNode = next;
}

{
int length = 0;

while(currentNode != null)
{
length++;
currentNode = currentNode.getNextNode();
}

return length;
}

ListNode insert(ListNode head , ListNode nodeToInsert, int position)
{
{
return nodeToInsert;
}

if(position > size + 1 || position < 1)
{
System.out.println("Valid positions goes from 1 to "+ (size+1));
}

if(position == 1)
{
return nodeToInsert;
}
else
{
int count = 1;
while (count < position - 1)
{
previousNode = previousNode.getNextNode();
count++;
}

ListNode currentNode = previousNode.getNextNode();
nodeToInsert.setNextNode(currentNode);
previousNode.setNextNode(nodeToInsert);
}

}

ListNode delete( ListNode head , int position)
{

if (position > size || position < 1)
{
System.out.println("Valid deletions position is from 1 to " + size);
}

if(position == 1)
{
return currentNode;
}
else
{
int count = 1;

while(count < position - 1)
{
previousNode = previousNode.getNextNode();
count++;
}

ListNode currentNode = previousNode.getNextNode();
previousNode.setNextNode(currentNode.getNextNode());
currentNode.setNextNode(null);
}