Skip to content

Instantly share code, notes, and snippets.

@ntub46010
Last active June 29, 2021 02:37
Show Gist options
  • Save ntub46010/1aa38cf238d43b514352510b40702c65 to your computer and use it in GitHub Desktop.
Save ntub46010/1aa38cf238d43b514352510b40702c65 to your computer and use it in GitHub Desktop.
public class LinkedList<E> {
private Node<E> first;
private Node<E> last;
private int size;
public int size() {
return this.size;
}
public E getFirst() {
return this.first.getData();
}
public E getLast() {
return this.last.getData();
}
private Node<E> getNode(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
Node<E> currentNode = this.first;
for (int i = 0; i < index; i++) {
currentNode = currentNode.getNext();
}
return currentNode;
}
public E get(int index) {
return getNode(index).getData();
}
public void add(E data) {
Node<E> node = new Node<>(data);
if (this.size == 0) {
this.first = node;
} else {
this.last.setNext(node);
}
this.last = node;
this.size++;
}
public void add(int index, E data) {
if (index < 0 || index > this.size) {
throw new IndexOutOfBoundsException();
}
if (index == this.size) {
add(data);
return;
}
Node<E> node = new Node<>(data);
if (index == 0) {
node.setNext(this.first);
this.first = node;
} else {
Node<E> previousNode = getNode(index - 1);
Node<E> nextNode = previousNode.getNext();
previousNode.setNext(node);
node.setNext(nextNode);
}
this.size++;
}
public void remove(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
if (this.size == 1) {
this.last = null;
}
this.first = this.first.getNext();
} else {
Node<E> previousNode = getNode(index - 1);
Node<E> targetNode = previousNode.getNext();
Node<E> nextNode = targetNode.getNext();
previousNode.setNext(nextNode);
if (index == size - 1) {
this.last = previousNode;
}
}
this.size--;
}
public void reverse() {
Node<E> previousNode = null;
Node<E> currentNode = this.first;
Node<E> nextNode;
while (currentNode != null) {
nextNode = currentNode.getNext();
currentNode.setNext(previousNode);
previousNode = currentNode;
currentNode = nextNode;
}
this.last = this.first;
this.first = previousNode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node<E> node = this.first;
while (node != null) {
sb.append(node.toString()).append(" ");
node = node.getNext();
}
return sb.toString();
}
}
public class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this.data = data;
}
public E getData() {
return data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
@Override
public String toString() {
return data.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment