Java Data Structure How to - Create Link list with int and double data








Question

We would like to know how to create Link list with int and double data.

Answer

/* w ww .  ja  v  a 2 s  .c o  m*/
public class Main{
  public static void main(String[] args) {
    AnotherLinkList theList = new AnotherLinkList();

    theList.insertFirst(12, 2.59);
    theList.insertFirst(24, 4.69);
    theList.insertFirst(36, 6.79);
    theList.insertFirst(48, 8.89);

    theList.displayList();

    Link f = theList.find(44);
    if (f != null)
      System.out.println("Found link with key " + f.key);
    else
      System.out.println("Can't find link");

    Link d = theList.delete(66); 
    if (d != null)
      System.out.println("Deleted link with key " + d.key);
    else
      System.out.println("Can't delete link");

    theList.displayList();
  }
}
class Link {
  public int key;

  public double data; 

  public Link next;

  public Link(int id, double dd) {
    key = id;
    data = dd;
  }

  public void displayLink() {
    System.out.print("{" + key + ", " + data + "} ");
  }
}

class AnotherLinkList {
  private Link first;

  public AnotherLinkList() {
    first = null;
  }

  public void insertFirst(int id, double dd) {
    Link newLink = new Link(id, dd);
    newLink.next = first;
    first = newLink; 
  }

  public Link find(int key) 
  {
    Link current = first; 
    while (current.key != key)
    {
      if (current.next == null)
        return null; // didn't find it
      else
        // not end of list,
        current = current.next; // go to next link
    }
    return current; // found it
  }

  //   delete link with given key
  public Link delete(int key) {
    Link current = first;
    Link previous = first;
    while (current.key != key) {
      if (current.next == null)
        return null; // didn't find it
      else {
        previous = current; // go to next link
        current = current.next;
      }
    } // found it
    if (current == first) // if first link,
      first = first.next; //    change first
    else
      // otherwise,
      previous.next = current.next; //    bypass it
    return current;
  }

  public void displayList() {
    System.out.print("List (first to last): ");
    Link current = first; 
    while (current != null) 
    {
      current.displayLink(); 
      current = current.next;
    }
    System.out.println("");
  }

}

The code above generates the following result.