环形链表(用双向链表实现)

public class CycleLink {

  Node head = null;
  Node tail = null;
  int size;

  class Node {
    Node next = null;
    Node previous = null;
    int data;

    public Node(int data) {
      this.data = data;
    }

    @Override
    public String toString() {
      return "previous: " + previous.data + "  next: " + next.data + "  data: " + data;
    }
  }

  public void addNode(int d) {
    Node newNode = new Node(d);
    if (head == null) {
      newNode.next = newNode;
      newNode.previous = newNode;
      head = newNode;
      tail = newNode;
      size = 1;
      return;
    }
    Node tailTmp = tail;
    tailTmp.next = newNode;
    newNode.previous = tailTmp;
    head.previous = newNode;
    newNode.next = head;
    tail = newNode;
    size++;
  }

  public Node getNode(int index) {
    if (index == 0) {
      return head;
    }
    if (index + 1 == size) {
      return tail;
    }
    int i = 1;
    Node curNode = head.next;
    while (curNode != null) {
      if (i == index) {
        return curNode;
      }
      curNode = curNode.next;
      i++;
    }
    return null;
  }

  public Node removeNode(Node remove) {
    Node previous = remove.previous;
    Node next = remove.next;
    if (remove.equals(head)) {
      head = next;
    }
    if (remove.equals(tail)) {
      tail = previous;
    }
    previous.next = next;
    next.previous = previous;
    size--;
    return remove;
  }

  public int size() {
    return size;
  }

  public static void main(String[] args) {
    CycleLink cycleLink = new CycleLink();
    cycleLink.addNode(1);
    cycleLink.addNode(2);
    cycleLink.addNode(3);
    System.out.println("size: " + cycleLink.size());
    for (int i = 0; i < cycleLink.size(); i++) {
      System.out.println(cycleLink.getNode(i));
    }
    System.out.println("---------------------------------");
    Node node1 = cycleLink.getNode(0);
    cycleLink.removeNode(node1);
    System.out.println("size: " + cycleLink.size());
    for (int i = 0; i < cycleLink.size(); i++) {
      System.out.println(cycleLink.getNode(i));
    }
    System.out.println("---------------------------------");
    Node node2 = cycleLink.getNode(1);
    cycleLink.removeNode(node2);
    System.out.println("size: " + cycleLink.size());
    for (int i = 0; i < cycleLink.size(); i++) {
      System.out.println(cycleLink.getNode(i));
    }
  }
}

你可能感兴趣的