Hello
i want to my LinkedList class implements Collection interface but need help on that
any suggestion/help.
this is the LinkedList class
/**
* Linked list implementation
*/
public class LinkedList
{
protected Node firstNode = null;
/**
* Returns true if list is empty
*/
public boolean isEmpty()
{
return firstNode==null;
}
/**
* Adds a new node to the front of the list
* @param o object to add
*/
public void add(Object o)
{
Node node = new Node(o, firstNode);
firstNode = node;
}
/**
* Adds an object to list at specified index
*/
public void add(Object o, int index)
{
if (index==0)
{
// add as first node
add(o);
}
else
{
// find node before it in list
Node prev = get(index-1);
if (prev!=null)
{
// and insert new node
prev.setNext(new Node(o, prev.getNext()));
}
}
}
/**
* Removes an indexed element from the list
* @param index index of node to remove
*/
public Object remove(int index)
{
Object result = null;
// find node in list
// also need to remember previous node so we can update it's next pointer
Node prev = null;
Node node = firstNode;
for (int i=0; node!=null && i<index; i++)
{
prev = node;
node = node.getNext();
}
if (node!=null)
{
// remove element from list
if (prev==null)
{
// remove first node
firstNode = node.getNext();
}
else
{
// remove node
prev.setNext(node.getNext(
));
}
result = node.getData();
node.setNext(null);
}
return result;
}
/**
* Returns node at a specified index
*/
protected Node get(int index)
{
Node node = firstNode;
for (int i=0; node!=null && i<index; i++)
{
node = node.getNext();
}
return node;
}
/**
* Returns a string representation of the elements in the list
*/
public String toString()
{
StringBuffer result = new StringBuffer();
result.append("");
Node next = firstNode;
while (next!=null)
{
result.append(next);
next = next.getNext();
if (next!=null)
{
result.append("");
}
}
result.append("");
return result.toString();
}
}
Start Free Trial