Skip to content

Instantly share code, notes, and snippets.

@Hc747
Created March 12, 2018 08:24
Show Gist options
  • Save Hc747/943d9222d9a2068967e4f96b4065d35e to your computer and use it in GitHub Desktop.
Save Hc747/943d9222d9a2068967e4f96b4065d35e to your computer and use it in GitHub Desktop.
package your.package.here;
/**
* @author Harrison, Alias: Hc747, Contact: harrisoncole05@gmail.com
* @version 1.0
* @since 12/3/18
*/
public class LinkedList<T> {
private Node head;
private int size;
public void add(T element) {
Node node = new Node(element);
if (head == null) {
head = node;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = node;
}
size++;
}
public void remove(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(String.format("Invalid index: %d", index));
}
if (index == 0) {
if (head != null) {
head = head.next;
}
} else {
Node current = head;
Node previous = current;
for (int i = 0; i < index; i++) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
size--;
}
private class Node {
Node(T value) {
this.value = value;
}
T value;
Node next;
}
public void print() {
Node current = head;
while (current != null) {
System.out.println(current.value);
current = current.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment