单向链表的节点类:publicclassNode{publicObjectdata;下一个公共节点;公共节点(对象e){this.data=e;}}双向链表的节点类:publicclassNode{publicObjecte;publicNodenext;publicNodepre;publicNode(){}publicNode(Objecte){this.e=e;下一个=空;pre=null;}}如何自己写一个链表?代码如下(以双向链表为例,有详细注释,单向链表同理):首先创建节点类包MutuLink;公共类节点{公共对象e;下一个公共节点;公共节点前;publicNode(){}publicNode(Objecte){this.e=e;下一个=空;前=空;}}然后创建一个链表类包MutuLink;公共类MyList{私有节点头;私有节点尾部;私有整数大小=0;publicMyList(){head=newNode();尾=新节点();head.next=null;尾巴.pre=null;}publicbooleanempty(){if(head.next==null)returntrue;返回假;}//找到你要找的索引节点的前一个节点publicNodefindpre(intindex){节点rnode=head;intdex=-1;while(rnode.next!=null){//找到插入节点的前一个节点if(dex==index-1){returnrnode;}rnode=rnode.next;敏捷++;}返回空值;}publicNodefindthis(intindex){Nodernode=head;//把rnode想象成一个指针,dex是指向的下标,这个地方很容易出错,因为指向最后一个节点时没有判断if会跳出循环intdex=-1;while(rnode.next!=null){if(dex==index)返回rnode;rnode=rnode.next;敏捷++;}if(dex==size-1){返回rnode;}//节点测试=newNode(newStudents("haha",1,2));返回空值;}//在链表的末尾添加一个节点publicvoidadd(Objecte){Nodenode=newNode(e);节点rnode=head;//如果是空链表则插入一个节点,该节点的pre不能指向前一个节点,必须为空if(this.empty()){rnode.next=node;节点。next.pre=null;tail.pre=节点;尺码++;}else{while(rnode.next!=null)rnode=rnode.next;rnode.next=节点;node.pre=rnode;tail.pre=节点;尺码++;}}//往链表的某个标签插入一个节点publicbooleanadd(intindex,Objecte){if(index<0||index>=size)returnfalse;节点节点=新节点(e);节点prenode=this.findpre(index);node.next=prenode.next;prenode.next.pre=节点;prenode.next=节点;node.pre=前节点;尺码++;返回真;}publicbooleanadd(intindex,MyListmyl){if(index<0||index>=size)returnfalse;Nodeprenode=this.findpre(index);//myl.tail.pre.next=prenode.next;//prenode.pre=myl.tail.pre;//tail.pre=null;//prenode.next=myl.head.next;//myl.head.next.pre=prenode;//头.next=空;myl.tail.pre.next=prenode.next;prenode.next.pre=myl.tail.pre.pre;myl.head.next.pre=prenode.pre;prenode.next=myl.head.next;myl.head=null;myl.tail=null;size+=myl.size;返回真;}publicObjectremove(intindex){Objectob=this.get(index);如果(索引<0||索引>=大小)返回null;//特殊情况,当移除的节点是最后一个节点时//通过绘制来写代码会比较复杂if(index==size-1){Nodeprenode=this.findpre(index);this.tail.pre=this.tail.pre.pre;this.tail.pre.next.pre=null;this.tail.pre.next=null;尺寸-;返回对象;}//比较复杂,画图解决else{Nodeprenode=this.findpre(index);prenode.next=prenode.next.next;prenode.next.pre.next=null;prenode.next.pre=prenode.next.pre.pre;尺寸-;返回对象;}}publicObjectget(intindex){Nodethisnode=this.findthis(index);返回这个节点.e;}publicintsize(){返回大小;}}
