與單鏈表的不一樣:新增一個對最後一個鏈結點的引用,使其能夠像在表頭插入鏈結點同樣在表尾插入結點;而若在單鏈表的表尾插入結點就須要遍歷整個鏈表直到表尾。java
//鏈尾插入 public void insertLast(long dd){ LinkD newLink = new LinkD(dd); if(isEmpty()) first = newLink; else last.next = newLink; last = newLink; }
//雙端鏈表 package Structure; class LinkD{ public long dData; public LinkD next; public LinkD(long d){ dData = d; } public void displayLink(){ System.out.print(dData+" "); } }//end class Link class FirstLastList{ private LinkD first; private LinkD last; public FirstLastList(){ first = null; last = null; } public boolean isEmpty(){ return (first==null); } public void insertFirst(long dd){ LinkD newLink = new LinkD(dd); if(isEmpty()) last = newLink; newLink.next = first; first = newLink; } //鏈尾插入 public void insertLast(long dd){ LinkD newLink = new LinkD(dd); if(isEmpty()) first = newLink; else last.next = newLink; last = newLink; } public long deleteFirst(){ long temp = first.dData; if(first.next==null) last=null; first = first.next; return temp; } public void displayList(){ System.out.print("List(first-->last): "); LinkD current = first; while(current!=null){ current.displayLink(); current = current.next; } System.out.println(""); } } public class firstLastListD { public static void main(String[] args){ FirstLastList theList = new FirstLastList(); theList.insertFirst(202); theList.insertFirst(221); theList.insertFirst(222); theList.insertFirst(232); theList.insertLast(33); theList.insertLast(313); theList.insertLast(303); theList.insertLast(323); theList.displayList(); theList.deleteFirst(); theList.deleteFirst(); theList.displayList(); } }