A completed implementation of linked lists. The Node class:
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;
}
}
The LinkedList class:
public class LinkedList {
private Node first;
public LinkedList() {
first = null;
}
// returns 'true' for an empty list and 'false' otherwise
public boolean isEmpty() {
return (first == null);
}
// returns the reference to the first node in the list
// if the list is empty, null is returned.
public Node getFirst() {
return first;
}
// the method adds the node to the front of the list.
// the 'next' field of the node is replaced by the reference to
// the rest of the list
// If the parameter is null, an error message is printed and
// the program stops
public void addFront(Node n) {
// before calling a method on n, need to make sure
// that n is not null
if (n == null) {
System.out.println("Cannot add a null element to the list");
System.exit(0);
}
// if we got here, n is not null
n.setNext(first);
first = n;
}
// the method removes the first node from the list.
// if the list is empty, an error message is printed and
// the program stops
public void removeFront() {
// before removing an element from a list, need to make sure that
// the list is not empty
if (first == null) {
System.out.println("Cannot remove an element from an empty list");
System.exit(0);
}
// if we got here, the list is not empty
first = first.getNext();
}
}
The testing program for LinkedList. It needs some printing! Think of
how we can print a linked list. We will work on it (and on
applications of linked lists) on Wednesday.
public class TestLinkedLists {
public static void main(String [] args) {
// testing nodes:
Node first = new Node(5);
Node second = new Node(6);
LinkedList list = new LinkedList();
// add the two nodes to the list
list.addFront(first);
list.addFront(second);
// Something to think about for Wednesday:
// how do we print the list?
}
}
This is an example from CSci 2101 course.