/* * File List.java * * This file define the class 'List'. * An object of type 'List' is a list of 'Node' (cf Node.java). * */ /* This is the class declaration. */ public class List { /* This variable is noted as private. It is */ /* only accessible within the class. */ private Node FIRST; // This is the first element of the list /* This is the default constructor method. */ List() { this.FIRST=null; } /* With this constructor method you can pass and array */ /* of int as argument. The list will be initialized */ /* with those values. */ List(int[] array) { this.FIRST=null; for (int i=0; i < array.length; i++ ) { this.append(array[i]); // The keyword this refers // to the current class. Here we call // the append method of the class. } } /* This method append a node of type 'Node' to the list. */ /* The value of the new node is the argument. */ public void append (int value) { Node toAppend; Node current = this.FIRST; /* If the list is empty the new 'Node' is the first. */ if (current == null) { current = new Node(value); this.FIRST=current; } /* Otherwise, we go to the end of the list to append */ /* the new 'Node'. */ else { while (current.getNext() != null) { current=current.getNext(); } toAppend = new Node(value); current.setNext(toAppend); } } /* We use a public method to return a private variable. */ public Node getFirst() { return this.FIRST; } /* We use a public method to set a private variable. */ public void setFirst(Node first) { this.FIRST=first; } /* This method allows to insert the value 'value'in the */ /* 'pos' position of the list. */ public void insert(int pos, int value) { Node toInsert = new Node(value); Node current = this.FIRST; /* If to be inserted in first position, add the new 'Node' */ /* at the beginning. */ if ( pos == 1 ) { toInsert.setNext(this.FIRST); this.FIRST=toInsert; } /* Otherwise looks for the correct position. */ else { for (int i = 1; i < pos-1; i++) { current=current.getNext(); } /* That's where we do the insert. */ toInsert.setNext(current.getNext()); current.setNext(toInsert); } } /* This method prints out the entire list, element by element. */ public void print() { Node current = this.FIRST; if (current == null ) { System.out.print("null\n"); } else { while (current.getNext() != null) { System.out.print(current.getValue()+" "); current=current.getNext(); } System.out.print(current.getValue()+"\n"); } } }