Finding and Deleting Specified Links : Your LinkedList « Collections « Java Tutorial






class Link {
  public int iData;

  public Link next;

  public Link(int id) {
    iData = id;
  }

  public String toString() {
    return "{" + iData + "} ";
  }
}

class LinkList {
  private Link first;

  public LinkList() {
    first = null;
  }

  public boolean isEmpty() {
    return (first == null);
  }

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

  public Link delete(int key) {
    Link current = first;
    Link previous = first;
    while (current.iData != key) {
      if (current.next == null)
        return null;
      else {
        previous = current;
        current = current.next;
      }
    }
    if (current == first)
      first = first.next;
    else
      previous.next = current.next;
    return current;
  }

  public Link find(int key) {
    Link current = first;
    while (current.iData != key) {
      if (current.next == null)
        return null;
      else
        current = current.next;
    }
    return current;
  }

  public String toString() {
    String str = "";
    Link current = first;
    while (current != null) {
      str += current.toString();
      current = current.next;
    }
    return str;
  }
}

public class MainClass {
  public static void main(String[] args) {
    LinkList theList = new LinkList();

    theList.insertFirst(22);
    theList.insertFirst(44);
    theList.insertFirst(66);
    theList.insertFirst(88);

    System.out.println(theList);

    System.out.println(theList.find(22));
    
    Link aLink = theList.delete(44);

    System.out.println(theList);
  }
}
{88} {66} {44} {22} 
{22} 
{88} {66} {22}








9.50.Your LinkedList
9.50.1.Demonstrating linked list
9.50.2.Finding and Deleting Specified Links
9.50.3.Double-Ended Lists: list with first and last references
9.50.4.Sorted Lists
9.50.5.A doubly-linked list
9.50.6.Iterators on a linked list
9.50.7.Linked List Entry
9.50.8.Demonstrating a stack implemented as a list
9.50.9.A simple linked List implementation
9.50.10.A simple Doubly Linked list class, designed to avoid O(n) behaviour on insert and delete.
9.50.11.A Queue Implemented by a Linked List
9.50.12.A class that wraps an array with a List interface.
9.50.13.List containing other lists
9.50.14.List implementation with lazy array construction and modification tracking.