title: Creating a getLast method for Linked Lists
body: <p>I'm trying to hand code a getLast method in Java. I know what I have to do, I'm just having trouble coding it. What I need to do is traverse the linked list until p.link points to null, then I can add to the end of the list. Here's what I have so far:</p>
  
  <pre><code>class MyLinkedList 
  {
     private class Node           
     {
        private Node link;
        private int x;
     }
     //----------------------------------
     private Node first = null;    
     //----------------------------------
     public void addFirst(int d)
     {
        Node newNode = new Node(); 
        newNode.x = d;            
        newNode.link = first;      
        first = newNode;           
     } 
  
     public void addLast(int q)
     {
        Node newNode = new Node();
        newNode.x = q;
        newNode.link = null;  //points to null because nothing should follow it
     //----------------------------------
     public void traverse()
     {
        Node p = first;
        while (p != null)            
        {
           System.out.println(p.x);  
           p = p.link;               
        }
     }
  }
  //==============================================
  class C15h1  
  {
     public static void main(String[] args)
     {
        MyLinkedList list = new MyLinkedList();
        list.addLast(4);
        list.addLast(5);
       list.addLast(6);
        list.addFirst(1);
        list.addFirst(2);
        list.addFirst(3);
        System.out.println("Numbers on list");
        list.traverse();
     }
  }
  </code></pre>