1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| public class SparseVector {
public Object valeur;
public SparseVector suivant;
public int length;
private Node tete;
public class Node {
public Object valeur;
private Node next;
public Node(int valeur) {
this.valeur = valeur;
this.next = null;
}
}
public SparseVector() {
this(10);
}
public SparseVector(int length) {
this.length = length;
}
// Obtenir la valeur de l'élément à la position index
public Object get(int index) {
if (index > length-1){
return null;
}else{
Node node = tete;
for (int i = 0; i <= index; i++) {
node = node.next;
}
return node;
}
}
// Ajouter ou mettre à jour l'élément à la position index
public void set(int index, Object value) {
Node newNode = new Node(valeur);
if (index == 0) {
newNode.next = tete;
tete = newNode;
}else{
Node node = tete;
while (--index > 0) {
node = node.next;
}
newNode.next = node.next;
node.next = newNode;
}
}
// Supprimer l'élément à la position index
public void remove(int index) {
Node temp = tete;
for (int i=0; i<index-1; i++) {
temp = temp.next;
}
Node next = temp.next.next;
temp.next = next;
}
// Longueur du vecteur creux
public int length() {
return length;
}
// Nombre d'éléments non nuls
public int size() {
int size = 0;
Node temp = tete;
while (length >= 0){
if(temp.next != null){
temp = temp.next;
size++;
}else{
temp = temp.next;
}
}
return size;
}
} |
Partager