Skip to content

Instantly share code, notes, and snippets.

@cavoirom
Last active May 29, 2019 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavoirom/bca5b378329a0ce751a69fd958b8a629 to your computer and use it in GitHub Desktop.
Save cavoirom/bca5b378329a0ce751a69fd958b8a629 to your computer and use it in GitHub Desktop.
package com.cavoirom.java.recursion.example;
public class IntLinkedList {
private Node first;
public IntLinkedList() {}
public void add(int data) {
Node newNode = new Node(data);
if (first == null) {
this.first = newNode;
} else {
addLast(first, newNode);
}
}
public void add(int index, int data) {
if (index < 0) {
throw new IndexOutOfBoundsException();
} else if (index == 0 && this.first == null) {
this.first = new Node(data);;
} else if (index == 0) {
this.first = new Node(data, this.first);
} else {
insert(index, 1, this.first, data);
}
}
public int remove(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException();
} else if (index == 0 && this.first == null) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
Node removedNode = this.first;
this.first = this.first.next;
return removedNode.data;
} else {
return remove(index, 1, this.first);
}
}
private int remove(int expectedIndex, int currentIndex, Node previousNode) {
if (previousNode == null) {
throw new IndexOutOfBoundsException();
} else if (expectedIndex == currentIndex && previousNode.next == null) {
throw new IndexOutOfBoundsException();
} else if (expectedIndex == currentIndex) {
Node removedNode = previousNode.next;
previousNode.next = previousNode.next.next;
return removedNode.data;
} else {
return remove(expectedIndex, currentIndex + 1, previousNode.next);
}
}
private void insert(int expectedIndex, int currentIndex, Node previousNode, int data) {
if (previousNode == null) {
throw new IndexOutOfBoundsException();
} else if (expectedIndex == currentIndex) {
previousNode.next = new Node(data, previousNode.next);
} else {
insert(expectedIndex, currentIndex + 1, previousNode.next, data);
}
}
private void addLast(Node currentNode, Node newNode) {
if (currentNode.next == null) {
currentNode.next = newNode;
} else {
addLast(currentNode.next, newNode);
}
}
private static class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment