Java实现链表能够很好的封装对指针的实现,让用户使用的时候不会感受到指针的繁琐,但是可能会带来效率的降低。
这个链表是一个单链表的实现,使用了链表迭代器,刚开始看的时候感觉有些很不舒服,但是使用起来明显能感受功能带来的效果,因为你可以脱离链表而独自操作,可以同时对链表进行前后的遍历。提高时间效率,但是同样也得操作带来了麻烦。我觉的还是直接使用链表比较好,但是作为一种思想,还是值得学习学习,说不定是因为现在水平太低呢,呵呵,留着备用吧,下面上代码
第一个是链表的节点实现
package com.bird.three; /** * @category 该类为链表的节点类,存储指针和数据 * @author Bird * */ public class ListNode {//具有包友好访问权限 Object element; ListNode next; ListNode(Object theElement){ this(theElement,null); } ListNode(Object theElement, ListNode n){ element = theElement; next = n; } }
第二个是枚举器,实现对提供表元素的访问
package com.bird.three; /** * @category 枚举器类,提供读取表元素的方法 * @author Bird * */ public class LinkedListItr { ListNode current;//记录当前节点位置,具有包访问权限 public LinkedListItr(ListNode theNode){ current = theNode; } public boolean isPastEnd(){ return current == null; } public Object retrieve(){//返回存储在当前位置上的元素 return isPastEnd() ? null : current.element; } public void advance(){//将当前位置推进到下一个节点位置 if(!isPastEnd()) current = current.next; } }
第三个链表的实现
package com.bird.three; /** * @category 链表的实现 * @author Bird * */ public class LinkedList { private static ListNode header; public LinkedList(){ header = new ListNode(null);//头结点赋值为空 } public boolean isEmpty(){ return header.next == null; } public void makeEmpty(){ header.next = null; } public LinkedListItr zeroth(){//返回对应于头结点的枚举器 return new LinkedListItr(header); } public LinkedListItr first(){//返回第一个节点的枚举器 return new LinkedListItr(header.next); } public LinkedListItr find(Object x){//根据指定的元素找到相对应的节点,并且返回迭代器 ListNode itr = header.next; while(itr != null && !itr.element.equals(x)) itr = itr.next; return new LinkedListItr(itr); } public LinkedListItr findPrevious(Object x){//注意,这个返回的是X的前驱节点 ListNode itr = header; while(itr.next != null && !itr.next.element.equals(x)) itr = itr.next; return new LinkedListItr(itr); } public void remove(Object x){ LinkedListItr p = findPrevious(x); if(p.current.next != null) p.current.next = p.current.next.next; } public void insert(Object x, LinkedListItr p){ if(p!=null && p.current != null) p.current.next = new ListNode(x,p.current.next); } public void printList(LinkedList theList){ if(theList.isEmpty()) System.out.println("Empty List"); else{ LinkedListItr itr = theList.first(); for(; !itr.isPastEnd(); itr.advance()) System.out.println(itr.retrieve()+" "); } System.out.println(); } public static void main(String[] args){ LinkedList list = new LinkedList(); System.out.println(header); System.out.println(header.next); list.printList(list); } }