Tuesday, September 20, 2011

LinkedList Implementation in java and basic operations like Insertion , deletion, modifying a node



package linkedlist;

public class Node<E> {
E data;
Node<E> next;

}




package linkedlist;

public class SinglyLinkedList<E> {
Node<E> start;
int size;

public SinglyLinkedList()
{
start = null;
size = 0;
}

public void add (E data)
{
insertAtLast(data);
}

public void insertAtLast(E data)
{
if(size == 0)
{
start = new Node<E>();
start.data = data;
start.next = null;
}
else
{
Node<E> currentNode = getNodeAt(size -1);
Node<E> tempNode = new Node<E>();
tempNode.data = data;
tempNode.next = null;
currentNode.next = tempNode;

}
size++;
}

public void insertAtFirst(E data)
{
if(size == 0)
{
start = new Node<E>();
start.data = data;
start.next = null;
}
else
{
Node<E> tempNode = new Node<E>();
tempNode.data = data;
tempNode.next = start;
start = tempNode;
}
size++;
}
public Node<E> getNodeAt(int pos) throws ArrayIndexOutOfBoundsException
{
Node <E>temp = start;
if((pos < 0 ) ||(pos > size))
{
throw new ArrayIndexOutOfBoundsException();
}

else
{
for(int count  = 0; count < pos; count++)
{
temp = temp.next;
}
}
return temp;

}
public void insertAt(int pos, E data)
{
if (pos == 0)
{
insertAtFirst(data);
}
else if(pos == size - 1)
{
insertAtLast(data);
}
else
{
Node<E> temp = getNodeAt(pos -1);
Node<E> newNode = new Node<E>();
newNode.data = data;
newNode.next = temp.next;
temp.next = newNode;
size++;
}
}

public Node<E> getFirst()
{
return getNodeAt(0);
}
public Node<E> getLast()
{
return getNodeAt(size -1);
}
public E removeAtFirst() throws ArrayIndexOutOfBoundsException
{
if(size <= 0)
{
throw new ArrayIndexOutOfBoundsException();
}

E data = start.data;
start = start.next;
size--;
return data;
}
public E removeAtLast() throws ArrayIndexOutOfBoundsException
{
if(size<=0)
{
throw new ArrayIndexOutOfBoundsException();
}
Node<E> temp =getNodeAt(size-2);
E data = temp.next.data;
temp.next = null;
size--;
return data;
}
public E removeAt(int pos) throws ArrayIndexOutOfBoundsException
{
if(( pos < 0 ) || (pos > size))
{
throw new ArrayIndexOutOfBoundsException();
}
Node <E> temp = getNodeAt(pos-1);
E data = temp.next.data;
temp.next=temp.next.next;
size--;
return data;
}
public int size()
{
return size;
}
public String toString()
{
StringBuilder string = new StringBuilder();
if(size == 0)
{
return "";
}
Node<E> temp = new Node<E>();
temp = start;
while(temp.next != null)
{
string.append(temp.data).append(",");
temp = temp.next;
}
string.append(temp.data);
return string.toString();
}
public static void main(String [] args)
{
SinglyLinkedList<Integer> list = new SinglyLinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list.toString());
System.out.println(list.removeAtFirst());
System.out.println(list.removeAtLast());
System.out.println(list.toString());
}
}

No comments:

Post a Comment