linkedlist.java

来自「Java 入门书的源码」· Java 代码 · 共 87 行

JAVA
87
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Implements the LinkedList data structure.
 */

public class LinkedList {

  class Node {
    Object data;
    Node next;
 
    public Node(Object o, Node n){
      data = o;
      next = n;
    }
  }

  private Node head;
  private Node previous;
  private Node current;
  
  public LinkedList() {
    head = null;
    previous = null;
    current = null;
  }
  public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
      head = n;
    else 
      previous.next = n;
    current = n;
  }
  public void remove() {
    if (head != null){
      if (previous == null)
        head = head.next;
      else 
        previous.next = current.next;
      current = current.next;
    }
  }
  public Object getData(){
    if (current != null) 
      return current.data;
    return null;
  }
  public boolean atEnd() {
    return current == null;
  }
  public void advance(){
    if (!atEnd()){
      previous = current;
      current = current .next;
    }
  }
  public void reset() {
    previous = null;
    current = head;
  }
  public void display() {
    reset();
    if (head != null) 
      do {
        System.out.println("  " + getData());
        advance();
      }while (!atEnd());
  }    
  public static void main(String [] args) {
    LinkedList list = new LinkedList();
    list.insert("Happy days");
    list.insert("Pie in the sky");
    list.insert("Trouble in River City");
    System.out.println("The original list is:");
    list.display();
    list.reset();
    list.advance();
    System.out.println("The current list element is " + list.getData());
    list.remove();
    System.out.println("The list, after removing the current element, is:");
    list.display();
  }
}    
  
            

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?