欢迎来到天天文库
浏览记录
ID:16007613
大小:52.50 KB
页数:16页
时间:2018-08-07
《java实现链表,双向链表42069》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、JAVA实现链表,双向链表42069//friendlydatasoclasslistcanaccessitdirectlyObjectdata;ListNodenext;ListNode(Objecto){data=o;next=null;}//Constructor:CreateaListNodethatreferstoObjectoandtothe//nextListNodeintheList.ListNode(Objecto,ListNodenextNode){data=o;next=nextNode;}//ReturntheObjectinthi
2、snodeObjectgetObject(){returndata;}ListNodegetnext(){returnnext;}}//ClassListdefinitionclassList{privateListNodefirstNode;privateListNodelastNode;privateStringname;//Stringlike"list"usedinprintingpublicList(Strings){name=s;firstNode=lastNode=null;}//Constructor:ConstructoranemptyL
3、istwith"List"asthenamepublicList(){this("list");}//InsertanObjectatthefrontoftheListIfListisempty,firstNode//andlastNoderefertosameObject.Otherwise,firstNodereferstonewnode.publicvoidinsertAtFront(ObjectinsertItem){if(isEmpty())//如果链表为空,返回true,否则返回false.firstNode=lastNode=newListN
4、ode(insertItem);elsefirstNode=newListNode(insertItem,firstNode);}//InsertanObjectattheendoftheListIfListisempty,firstNodeand//lastNoderefertosameObject.Otherwise,lastNode'snextinstancevariablereferstonewnode.publicvoidinsertAtBack(ObjectinsertItem){if(isEmpty())firstNode=lastNode=
5、newListNode(insertItem);elselastNode=lastNode.next=newListNode(insertItem);}//RemovethefirstnodefromtheList.publicObjectremoveFromFront()throwsEmptyListException{ObjectremoveItem=null;if(isEmpty())thrownewEmptyListException(name);removeItem=firstNode.data;//retrievethedataresetthe
6、firstNodeandlastNodereferencesif(firstNode.equals(lastNode))firstNode=lastNode=null;elsefirstNode=firstNode.next;returnremoveItem;}//RemovethelastnodefromtheListpublicObjectremoveFromBack()throwsEmptyListException{ObjectremoveItem=null;if(isEmpty())thrownewEmptyListException(name)
7、;removeItem=lastNode.data;//retrievethedataresetthefirstNodeandlastNodereferencesif(firstNode.equals(lastNode))firstNode=lastNode=null;else{ListNodecurrent=firstNode;while(current.next!=lastNode){current=current.next;}lastNode=current;current.next=null;}returnremoveItem;}//Returnt
8、rueiftheListisempty.publicboolean
此文档下载收益归作者所有