单向链表对于插入数据有很大的局限性,在做插入操作,空间复杂度有点大,双端链表就有效的改善了这一状况 Node类:package doubleendlinklist;/** * * Title:Node * Description:节点 * Company: *@aut
Node类: package doubleendlinklist; /** * *Title:Node
*Description:节点
*Company:
*@author mym *@date 2017-7-9下午7:41:16 *@version */ public class Node { public long data; //节点数据 public Node next; //下一个节点 public Node(long value){ this.data = value; } /** * *title:display
*function:显示当前表头数据
*@author mym */ public void display(){ System.out.print(data + " "); } } 双端链表类: package doubleendlinklist; /** * *Title:LinkList
*Description:相当于火车(包含多个火车节点)
*Company:
*@author mym *@date 2017-7-9下午7:44:18 *@version */ public class FirstLastLinkList { public Node first; //链表头头节点 public Node end; //尾节点 public FirstLastLinkList(){ first = null; //初始化 end = null; } /** * 插入节点,从头节点插入 */ public void insertNode(long value){ Node node = new Node(value); if(isEmpty()){ end = node; //如果为空,那么就把第一个设置的节点为尾节点 } node.next = first; //插入的节点的next指向当前存在的头节点 first = node; //把头节点指针指向刚插入的节点 } /** * 从尾节点开始插入 */ public void insertFromEndNode(long value){ Node node = new Node(value); if(isEmpty()){ first = node; }else end.next = node; end = node; } /** * 移出节点,从头节点移出 */ public long deleteNode(){ Node currentFirst = first; if(first != null){ if(first.next == null){ end = null; } first = first.next; //把头节点指针后移 } if(currentFirst == null){ return -1; } return currentFirst.data; } /** * 显示所有 */ public void display(){ Node currentNode = first; while(currentNode != null){ currentNode.display(); currentNode = currentNode.next; //指针后移一位 } System.out.println(); //换行 } /** * 根据数据查询节点 */ public Node selectNode(long value){ Node currentNode = first; //假设是头节点 while(currentNode != null && currentNode.data != value){ currentNode = currentNode.next; } return currentNode; } /** * 根据数据删除节点 */ public void deleteNode(long value){ Node deleteNode = null; Node preNode = first; //当前删除节点的前节点 if(first.data == value){ deleteNode(); //直接调用之前的删除头节点的方法 }else{ deleteNode = first.next; while(deleteNode.data != value){ preNode = deleteNode; deleteNode = deleteNode.next; } preNode.next = deleteNode.next; } } public boolean isEmpty(){ return first == null; } }