Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package node;
- public class Nodes {
- public static void main(String[] args) {
- NodeIterative<Integer> n = new NodeIterative<>(10);
- n.append(20);
- n.append(30);
- n.append(40);
- n.append(50);
- System.out.println(n.index(3));
- }
- }
- class NodeRecursive<T> {
- T x;
- NodeRecursive<T> next;
- NodeRecursive(T x) {
- this.x = x;
- }
- public void append(T other) {
- try {
- next.append(other);
- } catch (NullPointerException end_of_list) {
- this.next = new NodeRecursive<T>(other);
- }
- }
- public T index(int indice) {
- return indice == 0 ? x : next.index(indice - 1);
- }
- }
- class NodeIterative<T> {
- T x;
- NodeIterative<T> next;
- NodeIterative(T x) {
- this.x = x;
- }
- public void append(T other) {
- NodeIterative<T> item = this;
- while (item.next != null) {
- item = item.next;
- }
- item.next = new NodeIterative<T>(other);
- }
- public T index(int indice) {
- NodeIterative<T> item = this;
- for (int i = 0; i < indice; i++) {
- item = item.next;
- }
- return item.x;
- }
- }
Add Comment
Please, Sign In to add comment