Below are classes Node and LinkedList and the testing program for both. Note that this is not the best way of writing linked lists in Java (it allows unauthorized access to nodes), we will get to a better implementation later in the semester.

public class Node {
    private int data;
    private Node next;

    public Node(int d) {
	data = d;
	next = null; // can skip this line: null is the default value
    }

    public int getData() {
	return data;
    }

    // return the next node
    public Node getNext() {
	return next;
    }

    // set the node 
    public void setNext(Node n) {
	next = n;
    }
}



// WARNING: this is not the best way of writing a list class
// in Java. It's better to make nodes invisible from outside
// and let the outside world see the data only. 
// We choose a more transparent implementation so that it's 
// easier to test. 

public class LinkedList {
    private Node first;

    public LinkedList() {
	first = null;
    }

    public boolean isEmpty() {
	return (first == null);
    }

    public Node getFirst() {
	return first;
    }

    public void setFirst(Node n) {
	first = n;
    }

    public void addFront(Node n) {
	n.setNext(first); 
	first = n;
    }
}



public class TestLinkedLists {
    public static void main(String [] args) {
	// testing nodes:
	Node first = new Node(5);
	Node second = new Node(6);
	first.setNext(second);
	System.out.println( (first.getNext()).getData() );
	first.setNext(null);
	System.out.println(first.getNext());

	// testing linked lists:
	LinkedList list = new LinkedList();

	// add the two nodes to the list
	list.setFirst(first);
	list.addFront(second);

	// print the list
	System.out.println("The list elements are:");
	Node n = list.getFirst(); // if the list is empty, first is null
	while(n != null) {
	    int data = n.getData();
	    System.out.println(data);
	    n = n.getNext();
	}

	// adding an element to the back of the list
	Node oneMore = new Node(7);
	n = list.getFirst(); // if the list is empty, first is null
	if (n == null) {
	    list.setFirst(oneMore);
	} else {
	    Node last = null; // initialize last to keep the compiler happy
	    while(n != null) {
		last = n; // last is "one step behind" n 
		n = n.getNext();
	    }
	    last.setNext(oneMore);
	}

	// print the list after adding an element
	System.out.println("The list elements after adding one more are:");
	n = list.getFirst(); // if the list is empty, first is null
	while(n != null) {
	    int data = n.getData();
	    System.out.println(data);
	    n = n.getNext();
	}
    }
}


This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.