- #1

- 24

- 0

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;
}
```