/* *@date:08-07-06 *@descript:单链表的实现与应用 **/ public class LinList { public Node head;//头指针 public Node current;//当前节点位置 private int size;//数据元素个数 public LinList()//构造函数 { head=current=new Node(null); size=0; } public Node getHead() { return head; } //定位函数 public void index(int i) throws Exception { if(i<-1||i>size-1) { throw new Exception("参数错误!"); } if(i==-1) { return; } current=head.next; int j=0; while((current!=null)&&j size) { throw new Exception("参数错误!"); } index(i-1); //新节点的next域为current.next,而current的next域为新节点 current.setNext(new Node(obj,current.next)); size++; } //删除函数 public Object delete(int i)throws Exception { if(size==0) { throw new Exception("链表元素已空无法删除"); } if(i<0||i>size-1) { throw new Exception("参数错误!"); } index(i-1); Object obj=current.next.getElement(); //i-1个节点的next域指向i个节点的next域,让i节点脱链 current.setNext(current.next.next); size--; return obj; } //获取数据元素 public Object getData(int i)throws Exception { if(i<0||i>size) { throw new Exception("参数错误!"); } index(i); return current.getElement(); } //获取元素个数 public int size() { return size; } //判断是否为空 public boolean isEmpty() { return size==0; } //主函数 public static void main(String[] args) { LinList aLinList=new LinList(); LinList bLinList=new LinList(); LinList cLinList=new LinList(); int n=10; try { for (int i=0; i
数据结构之单链表
最新推荐文章于 2022-04-05 19:39:00 发布