Last active
December 17, 2020 17:33
-
-
Save larswaechter/a6383ad29026c2907c42f0df783621ee to your computer and use it in GitHub Desktop.
Recursive Node class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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