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