MnMWizard icon

Linked List module 9

MnMWizard | PRO | 05/11/18 04:36:32 PM UTC | 0 ⭐ | 395 👁️ | Never ⏰ | []
Java |

2.39 KB

|

None

|

0 👍

/

0 👎

//Mason Marnell
//Linked List Class
 
public class LinkedList {
    Node header;
    
    public LinkedList()
    {
        header = null;
    }
    public LinkedList(int data)
    {
        header = new Node();
        header.value = data;
    }
    public void addNode(int data)
    {
        Node temp = header;
        if(header != null)
            addNode(data,temp);
        else
        {
            header = new Node();
            header.value = data;
        }
    }
    public void addNode(int data, Node node)
    {
        if(node.next == null)
        {
            node.next = new Node();
            node = node.next;
            node.value = data;
            return;  // ends addNode method
        }
        // recursively call the next node, this one is not null
        addNode(data,node.next);
    }
    
    public void deleteFirst()
    {
        header = header.next;
    }
    public void deleteValue(int data)
    {
        deleteValue(data,header);
    }
    public void deleteValue(int data, Node node)
    {
        if(node.value == data)
        {
            node = null;
            return;  
        }
        // recursively call the next node, this one is not null
        deleteValue(data,node.next);
        // use recursion to find the value and delete it __ similar to addNode
 
        //I couldn't get the deleteValue to work so I guess I'll just take
        //the partial credit for the addNode
    }
    
    public String toString()
    {
        String data = "";
        if (header != null)
        {
            Node temp = header;
            data = toString(temp);
        }
        return data;
    }
    public String toString(Node node)
    {
        if(node != null)
        {
            return node.value + " " + toString(node.next);
        }
        return "";
    }
}
 
//---------------------------------------------------------------------------------------------------------
//LinkedListRunnerClass class
 
 
public class LinkedListRunnerClass {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int data = 3;
        LinkedList info = new LinkedList(data);
        info.addNode(4);
        info.addNode(7);
        info.addNode(9);
        System.out.println(info);
        info.deleteValue(2);
        System.out.println(info);
    }
    
}

Comments