在Java程序设计语言中,所有链表实际上都是双向链接的,即每个节点除了有放着后继的引用外,还存放着指向前驱结点的引用。Java中的LinkList类就实现了双向链表。listIterator可以实现对链表的双向遍历。
链表不支持快速地随机访问。如果要查看链表中第n个元素,就必须从头开始,越过n-1个元素。没有捷径可走。 鉴于这个原因,在程序需要采用整数索引访问元素时,程序员通常不选用链表。LinkedList中的get()方法可以访问某个特定元素,但是这个方法的效率并不太高。get()方法只是做了微小的优化:如果索引大于size()/2,就从列表尾端开始搜索元素。使用链表惟一理由是尽可能地减少在列表中间插入或删除元素所付出的代价。如果列表只有少数几个元素,就完全可以使用ArrayList.
如果要实现单向链表,可以使用内部类及节点概念的方式,充分利用面向对象思想来生成一个单项链表,也是比较简单的。一下代码就是对单向链表的一种实现方式:
package com.singlyLinkedList; /** * 使用节点和内部类的方式实现Java中的单向链表操作 * @author Birkhoff * */ class Link{ class Node{ private String name; //保存节点的名字 private Node next; //保存下一个节点 public Node(String name){ this.name=name; } public String getName(){ return this.name; } //给节点增加后继节点 public void addNode(Node newNode){ if(this.next==null){//后面没有东西 this.next=newNode; }else{ this.next.addNode(newNode); //向下继续查 } } //打印节点,如果该节点存在后继节点,则一同打印 public void printNode(){ System.out.print(this.name+"-->"); if(this.next!=null){ this.next.printNode(); //向下继续列出 } } //从根节点逐个查找匹配节点 public boolean searchNode(String name){ if(this.name.equals(name)){ return true; }else{ if(this.next!=null){ return this.next.searchNode(name); }else{ return false; } } } //删除某一个节点,删除时,要改变前驱节点的的指向 public void deleteNode(Node preNode,String name){ if(this.name.equals(name)){ preNode.next=this.next; }else{ this.next.deleteNode(this, name); } } }; private Node root; //要定义出根节点 public void add(String name){ Node newNode=new Node(name); if(this.root==null){//如果没有根节点,则把第一个作为根节点 this.root=newNode; }else{ this.root.addNode(newNode); } } //从根节点开始打印整个单向链表 public void print(){ if(this.root!=null){ this.root.printNode(); } } //在链表中逐个查找指定节点 public boolean search(String name){//指定查找的名字 if(this.root!=null){ return this.root.searchNode(name); }else{ return false; } } //删除链表中某个节点 public void delete(String name){ if(this.search(name)){ //判断此节点是否存在 if(this.root.name.equals(name)){ if(this.root.next!=null){ this.root=this.root.next; //改变根节点 }else{ this.root=null; //取消 } }else{ if(this.root.next!=null){ this.root.next.deleteNode(root, name); } } } } } public class LinkNodeDemo { /** * @param args */ public static void main(String[] args) { Link link=new Link(); link.add("根节点"); link.add("第一节点"); link.add("第二节点"); link.add("第三节点"); link.add("第四节点"); link.add("第五节点"); link.add("第六节点"); link.print(); System.out.println(); System.out.println(link.search("第X节点")); link.delete("第四节点"); link.delete("根节点"); link.print(); } } /** * 说明:以上代码源自魔乐科技李兴华老师的视频,特此声明。 */