Eternal Punishment
Eternal Punishment

Reputation: 131

adding a node at the end of a Linked List (java)

This is my code for the linked list (not the main). The method "addLast" gives me the following error and i'm not sure how to resolve it: "non-static variable cannot be referenced from a static context". It is talking about this line: return new Node(x,null); I'd appreciate any help as to how to resolve this issue. Thank you

public class LinkedList
{

  private class Node 
    { 
        int item;
        Node link;

        public Node ()
        {
            item = Integer.MIN_VALUE;
            link = null;

        }

        public Node (int x, Node p)

        {  
            item = x;
            link = p;

        }

    } //End of node class


    private Node head;


    public LinkedList()
    {
        head = null;
    }

    //adds a node to the start of the list with the specified data
    //added node will be the first node in the list

    public void addToStart(int x)
    {
        head = new Node(x, head);
    }


    //adds a number at end of list 
    public static Node addLast(Node header, int x)
    { 
        // save the reference to the header so we can return it. 
        Node ret = header; 

        // check base case, header is null. 
        if (header == null) { 
            return new Node(x, null); 
        } 

        // loop until we find the end of the list 
        while ((header.link != null)) { 
            header = header.link; 
        } 

        // set the new node to the Object x, next will be null. 
        header.link = new Node(x, null); 
        return ret; 
    }


    //displays the list
    public void printList()
    {
        Node position = head;
        while(position != null)
        {
            System.out.print(position.item + " ");
            position = position.link;
        }

        System.out.println();
    }
}

Upvotes: 1

Views: 2762

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126526

Remove the static qualifier from addLast -- it needs to be non-static to have a list to add to the end of. It also should not take (or return) a Node, as Node is a private nested class, so code outside this class doesn't know (or care) what a Node is, so can't have one to pass.

public void addLast(int x) {
    if (head == null) head = new Node(x, null);
    else {
        Node p = head;
        while (p.link != null) p = p.link;
        p.link = new Node(x, null); } }

Upvotes: 0

Matt
Matt

Reputation: 73

The answer is in the error line:

non-static variable cannot be referenced from a static context

Remove the static for the method addLast.

public Node addLast(Node header, int x) 
{
  ....
}

Upvotes: 0

August
August

Reputation: 12568

Here are two solutions:

Make Node a static nested class:

private static class Node { ... }

Or, make the addLast method an instance method:

public Node addLast(Node header, int x) { ... }

Upvotes: 1

Related Questions