JAVA基础(64)---双向链表

版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/84259190

 双向链表的实现

package org.lanqiao.doublelink;

public class DoubleLink{
	 
	  /**
	   * Node<AnyType>类定义了双向链表中节点的结构,它是一个私有类, 而其属性和构造函数都是公有的,这样,其父类可以直接访问其属性
	   * 而外部类根本不知道Node类的存在。
	   * 
	   * @author admin
	   *            类型
	   * @param Data
	   *            是节点中的数据
	   * @param pre
	   *            指向前一个Node节点
	   * @param next
	   *            指向后一个Node节点
	   */
	  private class Node {
	    public Node pre;
	    public Node next;
	    public Object data;
	 
	    public Node(Object data, Node pre, Node next) {
	     this.data = data;
	     this.pre = pre;
	     this.next = next;
	    }
	 
	    public Node() {
	     this.data = null;
	     this.pre = null;
	     this.next = null;
	    }
	  }
	 
	  // 下面是DoubleLinkedList类的数据成员和方法
	  private int theSize;//链表中元素的个数
	  private Node Header;//头节点
	  private Node Tail;//尾节点
	 
	  /*
	   * 构造函数 我们构造了一个带有头、尾节点的双向链表 头节点的Next指向尾节点 为节点的pre指向头节点 链表长度起始为0。
	   */
	  public DoubleLink() {
	 
	    theSize = 0;
	    Header = new Node(null, null, null);
	    Tail = new Node(null, Header, null);
	 
	    Header.next = Tail;
	  }
	 /*
	  * 向链表中添加一个节点
	  */
	  public void add(Object item) {
	 
	    Node aNode = new Node(item, null, null);
	 
	    Tail.pre.next = aNode;
	    aNode.pre = Tail.pre;
	    aNode.next = Tail;
	    Tail.pre = aNode;
	 
	    theSize++;
	  }
	 /*
	  * 判断链表是否为空
	  */
	  public boolean isEmpty() {
	    return (this.theSize == 0);
	  }
	 
	  public int size() {
	    return this.theSize;
	  }
	 
	  public Object getInt(int index) {
	 
	    if (index > this.theSize - 1 || index < 0)
	    {
	    	System.out.println("索引超出了范围");
	    }
	 
	    Node current = Header.next;
	 
	    for (int i = 0; i < index; i++) {
	     current = current.next;
	    }
	 
	    return current.data;
	  }
	 /*
	  * 遍历双向链表
	  */
	  public void print() {
	 
	    Node current = Header.next;
	 
	    while (current.next != null) {
	 
	     System.out.println(current.data.toString());
	 
	     current = current.next;
	    }
	 
	  }
	 
	  public static void main(String[] args) {
	    DoubleLink dLink = new DoubleLink();
	 
	    dLink.add("zhb");
	    dLink.add("zzb");
	    dLink.add("zmy");
	    dLink.add("zzj");
	 
	    System.out.println("size : " + dLink.size());
	    System.out.println("isEmpty? : " + dLink.isEmpty());
	    System.out.println("3 : " + dLink.getInt(2));
	    dLink.print();
	  }
	}

猜你喜欢

转载自blog.csdn.net/yj201711/article/details/84259190
今日推荐