Skip to content

Instantly share code, notes, and snippets.

@wkdalsgh192
Created June 9, 2021 15:13
Show Gist options
  • Save wkdalsgh192/bdd40f977364b049adfc6677dc14ef85 to your computer and use it in GitHub Desktop.
Save wkdalsgh192/bdd40f977364b049adfc6677dc14ef85 to your computer and use it in GitHub Desktop.
package dataStructure;
public class CustomLinkedList<E> {
// Linked List Node
private CustomNode<E> head; // head node
private CustomNode<E> tail; // tail node
private int size;
public int size() {
return size;
}
public CustomNode<E> get(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException();
CustomNode<E> x = head;
for (int i=0;i<index;++i) x = x.next;
return x;
}
public void addFirst(E value) {
// Create a new node with given data
CustomNode<E> nn = new CustomNode<E>(value);
nn.next = head; // new node points to the head node
head = nn; // the new node becomes the head
size++; // increment the size
// if there's only one node in the linked list, head and tail should be same.
if (head.next == null) tail = head;
}
public void add(E value) {
addLast(value);
return;
}
public void addLast(E value) {
CustomNode<E> nn = new CustomNode<E>(value);
if (size == 0) {
addFirst(value);
return;
}
tail.next = nn;
nn = tail;
size++;
}
public void add(int index, E value) {
if (index < 0 || index > size) throw new IndexOutOfBoundsException();
if (index == 0) {
addFirst(value);
return;
}
if (index == size) {
addLast(value);
return;
}
// get the prev point at the index
CustomNode<E> prev = get(index-1);
CustomNode<E> next = prev.next;
CustomNode<E> nn = new CustomNode(value);
// Unlink the next node from the prev
prev.next = null;
// prev points to the new node
prev.next = nn;
// new node points to the next node
nn.next = next;
size++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment