基于利用指针对线性表的实现(单链表)

来源:互联网 发布:大数据专业课程有哪些 编辑:程序博客网 时间:2024/06/07 22:43
    链表是由一系列表的结点的对象组成。因为结点是一个独立的对象,因此能够实现独立的节点类。
/*一个链表的节点*/public class Link {private Object element;//该节点的对象private Link next; //指向链表的下一个节点Link(Object item, Link nextvalue){//构造方法1element = item;next = nextvalue;}Link(Link nextvalue){//构造方法2next = nextvalue;}Link next(){//获得下一个节点return next;}Link setNext(Link nextvalue){//设置下一个节点,成功后返回下一个节点return next = nextvalue;}Object element(){//获得该节点的对象return element;}Object setElement(Object item){//设置该节点的对象,成功后返回该对象return element = item;}}//class Link

    每个节点只有一个指向表中的下一个节点的指针,因此实现的线性表为单链表,

    实现的单链表具有表头结点。表头结点是表的第一个结点,他与表中其他元素一样,只是他的值被忽略,不被看作表中的实际元素。添加表头结点的目的是使当前指针current指向当前元素的前驱结点,使得插入等操作变得简易,降低源代码的复杂性。(注:当当前指针current指向当前结点时,向当前位置插入新对象时,需要从头结点依次向后寻找,知道找到当前元素的前驱结点后,才能进行添加。并且需要考虑链表中无节点与只有一个结点的特殊情况。)

/*链表:利用指针实现*/public class LinkList implements List{private Link head; //指向表的头结点private Link tail;//指向表的尾节点protected Link current; //保存当前节点LinkList(int size){//构造方法-忽略大小setup();}LinkList(){//无参构造方法setup();}private void setup(){//初始化操作tail = head = current = new Link(null);//创造头结点}public void clear(){//从列表中移除所有的对象head.setNext(null);//终止访问其他节点current= tail = head;//重新初始化}//在当前位置插入对象public void insert(Object item){assert (current != null) : "无当前元素";current.setNext(new Link(item, current.next()));if(tail == current){tail = current.next();}}//从链表尾部添加对象public void append(Object item){tail.setNext(new Link(item, null));tail = tail.next();}//移除并返回当前对象public Object remove(){if(!isInList()){return null;}else{Object item = current.next().element();//得到当前对象的值if(tail == current.next()){//设置尾结点tail = current;}current.setNext(current.next().next());//从链表中中移除对象return item;//返回移除的值}}//移除所有对象public void removeAll(){head.setNext(null);//终止访问其他节点current= tail = head;//重新初始化}//设置当前位置为第一个位置public void setFirst(){current = head;}//移动当前位置至下一位置public void next(){if(current != null){current = current.next();}}//移动当前位置至上一位置public void previous(){if((current == null) || (current == head)){//上一位置无对象current = null;return;}Link temp = head;while((temp != null) && (temp.next() != current)){//从头结点开始检索temp.next();}current = temp;}//返回链表的长度public int length(){int cnt = 0;for(Link temp = head.next(); temp != null; temp = temp.next()){cnt++;}return cnt;}//设置当前位置至指定位置public void setPosition(int pos){current = head;for(int i=0; (current != null) && (i < pos); i++){current = current.next();}}//设置当前对象的值public void setValue(Object item){assert isInList() : "链表内无该对象";current.next().setElement(item);}//获得当前对象的值public Object currentValue(){if(!isInList()){return null;}return current.next().element();}//是否为空链表public boolean isEmpty(){return head.next() == null;}//是否在列表中public boolean isInList(){return (current != null) && (current.next() != null);}//打印链表public void print(){if(isEmpty()){System.out.println("()");}else{System.out.print("(");for(setFirst(); isInList(); next()){System.out.print(currentValue()+" ");}System.out.println(")");}}}//class LinkList


0 0
原创粉丝点击