package mylinkedlist;
import java.util.Collection;
import java.util.Iterator;
public class LinkedList<T> implements java.util.Collection<T>
{
LLNode<T> head;
LLNode<T> tail;
int count;
LinkedList()
{
head = tail = null;
count = 0;
}
public Iterator<T> iterator()
{
return new LLIterator(this);
}
void addAtBeginning(T n)
{
count++;
LLNode<T> ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
ln.next = head;
head = ln;
}
}
public boolean isEmpty()
{
return head == null;
}
void printAllItems()
{
for (LLNode<T> i = head; i != null; i = i.next)
System.out.println(i.value);
}
T front()
{
if (head == null)
return null;
else
return head.value;
}
T rear()
{
LLNode<T> prev = null;
for (LLNode<T> i = head; i != null; i = i.next)
prev = i;
if (prev == null)
return null;
else
return prev.value;
}
public int size()
{
// int count = 0;
// for (LLNode i = head; i != null; i = i.next)
// count++;
return count;
}
void addAtEnd(T n)
{
// LLNode prev = null;
// for (LLNode i = head; i != null; i = i.next)
// prev = i;
//
// if (prev == null)
// ;
// else
// {
// prev.next = new LLNode(n);
// count++;
// }
count++;
LLNode ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
tail.next = ln;
tail = ln;
}
}
@Override
public boolean add(Object arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean addAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void clear() {
head = tail = null;
count = 0;
}
@Override
public boolean contains(Object arg0) {
for (T x : this)
if (x == arg0)
return true;
return false;
}
@Override
public boolean containsAll(Collection c)
{
for (Object x : c)
if (contains(x) == false)
return false;
return true;
}
@Override
public boolean remove(Object arg0) {
if (count == 1 && head.value == arg0)
{
head = tail = null;
count--;
return true;
}
LLNode<T> prev;
for(prev = head; prev != null && prev.next.value != arg0; prev = prev.next)
{ // do nothing
}
if (prev == null || prev.next.value != arg0)
return false;
else
{
prev.next = prev.next.next;
count--;
return true;
}
// we didn't handle where it is the first item
}
@Override
public boolean removeAll(Collection c) {
for (Object x : c)
remove(x);
return true;
}
@Override
public boolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object[] toArray() {
Object [] retval = new Object[count];
int i = 0;
for (T x : this)
{
retval[i] = x;
i++;
}
return null;
}
@Override
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
//void swap(LL a, LL b)
//{
// LL t = new LL();
// t.head = a.head;
// t.tail = a.tail;
// t.count = a.count;
//
// a.head = b.head;
// a.tail = b.tail;
// a.count = b.count;
//
// b.head = t.head;
// b.tail = t.tail;
// b.count = t.count;
//}
//
//System.out.println(s == t);
Thursday, July 22, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment