/**
* creating LinkedList that use private variables of Node
* Single LinkedList
*
* @author MUHAMMAD AZRI BIN JASNI @ ABDUL RANI
* @version 10 OCTOBER 2012
*/
public class LinkedList
{
public Node head;//head should always point to the first nod
public Node tail;
public Node current;
private int counter=0;
public LinkedList() {}
public int size()
{
return counter;
}
public boolean isEmpty()
{
return (head==null);
//return (size()==0);
}
public Node getFirst()
{
return head;
}
public Node getNext()
{
//return current.link;
return current.getLink();
}
public void insertAtFront(int data)
{
Node newNode = new Node(data);
if (isEmpty())
{
//head = new Node();
//tail = new Node();
head = newNode;
tail = newNode;
}
else
{
newNode.setLink(head); //link of newNode was set to be the same as address stored in head
head = newNode; //head store the address of newNode
}
newNode = null;
counter++;
}
public void insertAtBack(int data)
{
Node newNode = new Node(data);
if (isEmpty())
{
head = newNode;
tail = newNode;
}
else
{
tail.setLink(newNode);
tail = tail.getLink();
}
newNode = null;//remove reference at the end of operation
counter++;
}
public void removeFromFront()
{
if (isEmpty())
{
System.err.println("List is Empty, can't remove element from front.");
}
else
{
current = head;
head = head.getLink();
current.setLink(null);
counter--;
current = null;//remove reference at the end of operation
}
}
public void removeFromBack()
{
if (isEmpty())
{
System.err.println("List is Empty, can't remove element from back.");
}
else
{
current = head;
while (current.getLink()!=tail)
{
current = current.getLink();
}
tail = current;
current.setLink(null);
counter--;
current = null;//remove reference at the end of operation
}
}
public void display()
{
//current = new Node();
String output = "[";
if (! isEmpty())
{
current = head;//take address so it point to first node
while (current != null)
{
output += current.getData();
if (current.getLink() != null)
{
output += ", ";
}
current = getNext();//current = current.link;
}
}
output += "]";
System.out.println(output);
current = null;//remove reference
}
}