I've implemented a singly linked list in Java as a practice exercise and would appreciate a review.
LinkedList.java
public class LinkedList {
private Node head;
private int size;
public LinkedList() {
}
public void addToEnd(char data) {
addAtIndex(data, size);
}
public void addToBeginning(char data) {
addAtIndex(data, 0);
}
public void addAtIndex(char data, int index) {
Node temp = new Node(data);
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
temp.setNextNode(head);
head = temp;
incrementCount();
} else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.getNextNode();
}
temp.setNextNode(current.getNextNode());
current.setNextNode(temp);
incrementCount();
}
}
public void deleteFromBeginning() {
deleteFromIndex(0);
}
public void deleteFromEnd() {
deleteFromIndex(size - 1);
}
public void deleteFromIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
head = head.getNextNode();
decrementCount();
} else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.getNextNode();
}
current.setNextNode(current.getNextNode().getNextNode());
decrementCount();
}
}
public char getFirst() {
return getAtIndex(0);
}
public char getLast() {
return getAtIndex(size - 1);
}
public char getAtIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else {
Node current = head;
for (int i = 0; i < index && current != null; i++) {
current = current.getNextNode();
}
return current.getData();
}
}
public void decrementCount() {
size--;
}
public void incrementCount() {
size++;
}
public int getSize() {
return size;
}
public Node getHead() {
return head;
}
}
Node.java
public class Node {
private char data;
private Node next;
public Node(char data) {
this.data = data;
}
public char getData() {
return data;
}
public Node getNextNode() {
return next;
}
public void setData(char data) {
this.data = data;
}
public void setNextNode(Node next) {
this.next = next;
}
}