/** * A simple singly linked list, without tail pointer. * Naming follows Morelli, more or less. * * @author <a href="mailto:bremner@unb.ca">David Bremner</a> * @version 1.0 */ public class List{ private ListNode head; public List(){ head=null; } public void insertFirst(Object o){ ListNode node=new ListNode(o); node.setNext(head); head=node; } public void insertLast(Object o){ ListNode node=new ListNode(o); if (head==null){ head=node; } else { ListNode current=head; while(current.getNext()!=null){ current=current.getNext(); } current.setNext(node); } } public void print(){ for (ListNode current=head; current!=null; current=current.getNext()){ current.print(); } } public boolean isEmpty(){ return (head==null); } public Object removeFirst(){ if (head==null) throw new IllegalArgumentException( "No first element"); Object retVal=head.getData(); head=head.getNext(); return retVal; } public void removeLast(){ if (head==null) throw new IllegalArgumentException( "Empty List"); ListNode current=head; ListNode previous=null; while(current.getNext()!=null){ previous=current; current=current.getNext(); } if (previous != null) previous.setNext(null); else head = null; } public static void main(String[] args){ List test=new List(); test.insertLast("hello"); test.insertFirst("goodbye"); test.insertLast("are you still here"); test.print(); System.out.println(""); test.removeFirst(); test.print(); System.out.println(""); test.removeLast(); test.print(); System.out.println(""); test.removeLast(); test.print(); } } //