博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《Java数据结构和算法》双端链表
阅读量:7121 次
发布时间:2019-06-28

本文共 1696 字,大约阅读时间需要 5 分钟。

hot3.png

与单链表的不同:新增一个对最后一个链结点的引用,使其可以像在表头插入链结点一样在表尾插入结点;而若在单链表的表尾插入结点就需要遍历整个链表直到表尾。

//链尾插入 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 Linkclass 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(); }}

112733_2CZR_2653987.jpg

转载于:https://my.oschina.net/doudoulee/blog/643592

你可能感兴趣的文章