- #1
trouty323
- 24
- 0
Hello everyone. My task here is to construct my own linked list. The outer class is SLList and the inner class is Node. The problem that I seem to be having is when I try to use the fields of the outer class in the inner class, I am getting "cannot make static reference to the non-static field." My code is below. What is causing this to happen? I looked at the book and everything matches up. The only thing that seems to solve this problem is if I make the fields of the outer class static as well, but that is not how it is in the book.
Code:
public class SLList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
/**
* Default constructor
*/
public SLList() {
head = null;
tail = null;
size = 0;
}
/**
* Constructor for SLList
*
* @param head
* - beginning of the linked list
* @param tail
* - end of the linked list
*/
public SLList(Node<E> head, Node<E> tail, int size) {
this.head = head;
this.tail = tail;
this.size = size;
}
private static class Node<E> {
private E data;
private Node<E> next;
/**
* Constructor for Node
*
* @param data
* - is of type E. It can contain any data type
* @param next
* - next item in the list
*/
private Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
/**
* Adds an item to the tail of the linked list
*
* @param newItem
* - item to be added
*/
private void addTail(E newItem) {
if (tail == null) {
tail = new Node<E>(newItem, null);
size++;
} else {
tail.next = new Node<E>(newItem, null);
tail = tail.next;
size++;
}
}
/**
* Finds item in the linked list if it exists
*
* @param search
* - item to be searched for
* @return 0 if found, -1 if not found, -10 if empty list
*/
private int find(E search) {
if (head == null) {
return -10;
}
Node<E> p = head;
do {
if (search.compareTo(p.data) == 0) {
return 0;
} else {
return -1;
}
p = p.next;
} while (p != null);
}
/**
* Gets item at the specified index
*
* @param index
* - position where item is located
* @return data at specified index
*/
private E get(int index) {
if (head == null || index > size - 1) {
return null;
}
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
Node<E> p = head;
int count = 0;
while (count < index && p.next != null) {
p = p.next;
count++;
}
if (count != index) {
return null;
} else {
return p.data;
}
}
/**
* Sets the node at position index to item
*
* @param index
* - position to be changed
* @param item
* - item to be placed at position index
*/
private void set(int index, E item) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
Node<E> p = (Node<E>) get(index);
p.data = item;
}