intermediate/FunList

From ggc

Jump to: navigation, search

001 package intermediate;
002 
003 import wiki.Wiki;
004 
005 public class FunList
006 {
007   class Node
008   {
009     Object data;
010     Node next;
011   }
012 
013   private Node first;
014 
015   public void addFirst(Object object)
016   {
017     Node node=new Node();
018     node.data=object;
019     node.next=first;
020     first=node;
021   }
022 
023   public Object removeFirst()
024   {
025 
026     if(first==null)
027     {
028       return null;
029     }
030     else
031     {
032       Object result=first.data;
033       first=first.next;
034       return result;
035     }
036   }
037 
038   public void addLast(Object object)
039   {
040     if(first==null)
041     {
042       addFirst(object);
043     }
044     else
045     {
046       Node current=first;
047       while(current.next!=null)
048       {
049         current=current.next;
050       }
051       Node toAdd=new Node();
052       toAdd.data=object;
053       toAdd.next=null;
054       current.next=toAdd;
055     }
056   }
057 
058   /**
059    * adds the object toAdd after the target.  In the
060    * event the target does not exist, adds to the end
061    * of the list. 
062    @param target to object to look for
063    @param toAdd the object to add after target
064    */
065   public void addAfter(Object target, Object toAdd)
066   {}
067 
068   /**
069    * adds the object toAdd before the target.  In the
070    * event the target does not exist, adds to the beginning
071    * of the list. 
072    @param target to object to look for
073    @param toAdd the object to add before target
074    */
075   public void addBefore(Object target, Object toAdd)
076   {}
077 
078   public Object removeLast(Object object)
079   {
080     if(first==null)
081     {
082       return null;
083     }
084     else if(first.next==null)
085     {
086       return removeFirst();
087     }
088     else
089     {
090       Node current=first;
091       while(current.next.next!=null)
092       {
093         current=current.next;
094       }
095       Object result=current.next.data;
096       current.next=null;
097       return result;
098     }
099   }
100 
101   public String toString()
102   {
103     String total="";
104     Node current=first;
105     while(current!=null)
106     {
107       total+=current.data.toString()+"->";
108       current=current.next;
109     }
110     return total;
111   }
112 
113   public static void main(String[] args)
114   {
115     FunList list=new FunList();
116     list.addFirst("Hello");
117     list.addFirst("List");
118     //list.removeFirst();
119     //list.removeFirst();
120     //list.removeFirst();
121     Wiki.out.println(list);
122   }
123 }


Download/View intermediate/FunList.java





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter