双向链表java实现

import java.util.Iterator;

public class TwoWayLink implements Iterable {

  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 "data:" + data;
    }
  }

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

    Node tailTmp = tail;
    tailTmp.next = newNode;
    newNode.previous = tailTmp;
    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)) {
      next.previous = null;
      head = next;
    } else if (remove.equals(tail)) {
      previous.next = null;
      tail = previous;
    } else {
      previous.next = next;
      next.previous = previous;
    }
    size--;
    return remove;
  }

  public int size() {
    return size;
  }

  @Override
  public Iterator iterator() {
    return new Iterator() {
      int cursor;
      int lastRet = -1;

      @Override
      public boolean hasNext() {
        return cursor != size;
      }

      @Override
      public Object next() {
        lastRet = cursor;
        cursor++;
        return getNode(lastRet);
      }
    };
  }

  public static void main(String[] args) {
    TwoWayLink twoWayLink = new TwoWayLink();
    twoWayLink.addNode(1);
    twoWayLink.addNode(2);
    twoWayLink.addNode(3);
    System.out.println(twoWayLink.size());
    Iterator iterator = twoWayLink.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }

}

你可能感兴趣的