// File: PhotoGallery2.java
// Time-stamp: "2005-01-24 10:23:33 calvanese"
// Purpose: PhotoGallery: solution part 1 - iterative implementation

class Node {
  String info;
  Node next;
}

public class PhotoGallery2 {

  // representation of the objects
  private String url;
  private Node photolist;


  // pubblic methods

  public PhotoGallery2(String u) {
    url = u;
    photolist = null;
  }
  
  public String getUrl() {
    return url;
  }
  
  public int numPhoto() {
    int cont = 0; 
    Node p = photolist;
    while (p != null) {
      cont++;
      p = p.next;
    }
    return cont;
  }
  
  public void add(String photo) {
    if (!present(photo)) {
      Node aux = new Node();
      aux.info = photo;
      aux.next = photolist;
      photolist = aux;
    }
  }
  
  public void remove(String photo) {
    if (photolist == null)   // the element is not present and
      return;                // we do nothing
    else if (photolist.info.equals(photo)) 
      photolist = photolist.next; // we remove the first one
    else {
      Node p = photolist;
      while (p.next != null && !p.next.info.equals(photo))
        p = p.next;
      if (p.next.info.equals(photo))
        p = p.next.next;
      else      // the element is not present and
        return; // we do nothing
    }
  }

  /* alternatively, we can use a generator node
  public void remove(String photo) {
    Node aux = new Node(); // generator node
    aux.next = photolist;
    Node p = aux;
    while (p.next != null && !p.next.info.equals(photo))
      p = p.next;
    if (p.next.info.equals(photo))
      p = p.next.next;
    else      // the element is not present and
      return; // we do nothing
  }
  */

  public boolean present(String photo) {
    Node p = photolist;
    while (p != null) {
      if (p.info.equals(photo))
        return true;
      p = p.next;
    }
    return false;
  }

  public String[] returnAllPhotos() {
    String[] ris = new String[numPhoto()];
    int i = 0;
    Node p = photolist;
    while (p != null) {
      ris[i] = p.info;
      i++;
      p = p.next;
    }
    return ris;
  }

  /* alternatively, we can use the array to control the loop
  public String[] returnAllPhotos() {
    String[] res = new String[numPhoto()];
    Node p = photolist;
    for(int i = 0; i < res.length; i++) {
      res[i] = p.info;
      p = p.next;
    }
    return res;
  }
  */
  
  public void removeAll() {
    photolist = null;
  }
}
