0

So I have the following class and am trying to make a method where an array is converted to a node list. I tried a for loop but I can't get it through my mind trying to set the next for each value.

public class Node {
    public Node(int value, Node link) {
        data = value;
        next = link;
    }

    public void setData(int n) {
        data = n;
    }

    public void setNext(Node link) {
        next = link;
    }

    public int getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }

    private int data;
    private Node next;

    public Node arrayToList(int[] a) {
        for (int i = 0; i < a.length-1; i++) {
            Node n = new Node(a[i], //a[i+1] but it must be a Node, so how would you loop the next Node);
        }
    }
}

1 Answer 1

2

Just iterate the array in reverse order. Take care to save succ between iterations, and keep n ready for the final return.

public Node arrayToList(int[] a) {
  Node succ = null;
  Node n;
  for (int i = a.length-1; i >= 0; i--) {
    n = new Node(a[i], succ );
    succ = n;
  }
  return n;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.