单链表java实现

public class MyLink {

  Node head = null;
  int size;

  class Node {
    Node next = null;
    int data;

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

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

  //添加节点
  public void addNode(int d) {
    Node newNode = new Node(d);
    if (head == null) {
      head = newNode;
      size = 1;
      return;
    }
    Node tmp = head;
    while (tmp.next != null) {
      tmp = tmp.next;
    }
    tmp.next = newNode;
    size++;
  }

  //根据index获取节点
  public Node getNode(int index) {
    if (index == 0) {
      return head;
    }
    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) {
    if (remove.equals(head)) {
      Node next = head.next;
      head = next;
    } else {
      Node previous = head;
      Node curNode = previous.next;
      while (!curNode.equals(remove)) {
        previous = curNode;
        curNode = curNode.next;
      }
      previous.next = curNode.next;
    }
    size--;
    return remove;
  }

  //获取长度
  public int size() {
    return size;
  }

  //测试方法
  public static void main(String[] args) {
    MyLink myLink = new MyLink();
    myLink.addNode(1);
    myLink.addNode(2);
    myLink.addNode(3);
    for (int i = 0; i < myLink.size(); i++) {
      System.out.println(myLink.getNode(i));
    }
    System.out.println("----------------");
    Node node3 = myLink.getNode(2);
    myLink.removeNode(node3);
    for (int i = 0; i < myLink.size(); i++) {
      System.out.println(myLink.getNode(i));
    }
    System.out.println("----------------");
    Node node1 = myLink.getNode(0);
    myLink.removeNode(node1);
    for (int i = 0; i < myLink.size(); i++) {
      System.out.println(myLink.getNode(i));
    }
    System.out.println("----------------");
  }
}

你可能感兴趣的