Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Problem with creating my own linked list

$
0
0
hi i ma having a problem crating my own linked list and i have been trying for a while now to get it right but with no luck

At the minitue this is what i have


the ListNode
package linkedlist;

/**
 *
 * @author Dale
 */
public class ListNode 
{
    ListNode link;
    String data;
    
    
    //create default constructor
    ListNode()
    {
        link = null;
        data = "";
    } // end defualt constructor
    
    // constructor one-aurguments
    ListNode(String dataIn)
    {
        data = dataIn;
        link = null;
    } // end constructor One-argument

       
}



the linkedList
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkedlist;

/**
 *
 * @author Dale
 */
public class LinkedList 
{
    ListNode head;
    
    
    LinkedList()
    {
        head = null;
    }
    
   public void insertAtFront(ListNode obj)
   {
       ListNode current = head;
       head = obj;
       obj.link = current;
   } // end method for inserting a node at the frunt of the list
   
   public void viewAllData()
   {
       ListNode current = head;
       while(current != null)
       {
           System.out.println(current.data);
       }
       
   } // end method for inserting a node at the back of the list
}




and the test program
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkedlist;

/**
 *
 * @author Dale
 */
public class TestLinkedList {
    public static void main(String[] args)
    {
        // create the linked list
        LinkedList list = new LinkedList( );
        
        System.out.println("1: " + list.head);//#################
        
        // add a few nodes to the linked list
        ListNode node1 = new ListNode("Hello");
        System.out.println("2: data = " + node1.data + " link = "+ node1.link);//#################
        list.insertAtFront(node1);
        ListNode node2 = new ListNode("this is my linked list");
        System.out.println("3: data = " + node2.data + " link = "+ node2.link);//#################
        list.insertAtFront(node2);
       
        
        
        
    } // end main method
}




when i run this i get this output

1: null
2: data = Hello link = null
3: data = this is my linked list link = null


from this you can see that the first node i created for some reason does not point to the second node, i know that there will be a stupid mistake some were but i just cant find it.

any help is appreciated
thanks dale

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>