Skip to content

Instantly share code, notes, and snippets.

@larswaechter
Last active December 17, 2020 17:33
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 larswaechter/a6383ad29026c2907c42f0df783621ee to your computer and use it in GitHub Desktop.
Save larswaechter/a6383ad29026c2907c42f0df783621ee to your computer and use it in GitHub Desktop.
Recursive Node class
public class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
public int get(int index) {
assert index >= 0 && index < this.length();
Node node = this;
while (index-- > 0)
node = node.next;
return node.value;
}
public void set(int index, int value) {
assert index >= 0 && index < this.length();
Node node = this;
while (index-- > 0)
node = node.next;
node.value = value;
}
public void append(int value) {
if (this.hasNext())
this.next.append(value);
else
this.next = new Node(value);
}
public boolean hasNext() {
return this.next != null;
}
public boolean includes(int value) {
for (Node node = this; node != null; node = node.next)
if (node.value == value)
return true;
return false;
}
public int sum() {
if (this.hasNext())
return this.value + this.next.sum();
return this.value;
}
public int length() {
if (this.hasNext())
return 1 + this.next.length();
return 1;
}
@Override
public String toString() {
if (this.hasNext())
return this.value + ", " + this.next.toString();
return String.valueOf(this.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment