The List: 3/27
Welcome to the list.
- A list is an item followed by a list, OR
- A list is empty.
That is, a list is defined in terms of itself. This allows us to
define operations in terms of themselves.
Some simple operations:
- To add a new-item to the end of a list: if the list is empty,
say the list contains the new-item following by a list that is
empty. Otherwise, add the item to the rest of the list.
- To remove the first item from a list: if the list is empty,
return null, otherwise, set the first item to the second item, and
the rest of the list to the second item's rest of list, and return
the old first item.
- To count the number of items on the list: if the list is empty,
it has zero items, otherwise it has 1 plus the number of items on
the rest of the list.
- To return the item at the ith list item: if i is zero, then
return the item, otherwise return the item at i-1th item in the rest
of the list.
public class List
{
public Object item;
public List next;
public List()
{
item = null;
next = null;
}
public void add(Object obj)
{
if (next == null) {
next = new List();
item = obj;
} else {
next.add(obj);
}
}
public Object remove()
{
Object o = item;
if (next != null) {
item = next.item;
next = next.next;
}
return o;
}
public boolean isEmpty()
{
return next == null;
}
public int size()
{
if (isEmpty())
return 0;
else return 1 + next.size();
}
public Object get(int i)
{
if (isEmpty()) {
throw new IndexOutOfBoundsException();
}
if (i == 0) {
return item;
} else
return next.get(i-1);
}
static public void main(String args[])
{
List l = new List();
l.add("A");
l.add("B");
l.add("C");
System.out.println(l.size());
System.out.println(l.get(2));
System.out.println(l.remove());
System.out.println(l.remove());
System.out.println(l.remove());
System.out.println(l.remove());
}
}
bershad
Last modified: Fri Feb 27 13:04:59 PST 2004