双端链表:与单链表非常相似,但添加了一个特性:对最后一个链接点的引用,就像跟单链表的第一个链接点引用一样。(insertFirst)
单链表对最后的一个链接点也可以引用,方法是遍历到表尾,找到最后一个链接点,但是效率太低了,所以提出双端链表。
1 public class Link { 2 3 private int iData; 4 private double dData; 5 private Link next; 6 7 public Link(int i, double d) { 8 this.iData = i; 9 this.dData = d; 10 } 11 12 public void displayLink() { 13 System.out.println("{ " + iData + " , " + dData + " }"); 14 } 15 16 public Link getNext() { 17 return next; 18 } 19 20 public void setNext(Link next) { 21 this.next = next; 22 } 23 24 public int getiData() { 25 return iData; 26 } 27 28 public double getdData() { 29 return dData; 30 } 31 32 }
1 public class FirstLastLinkList { 2 3 private Link first; 4 5 private Link last; 6 7 public boolean isEmpty() { 8 return first == null; 9 } 10 11 public void insertFirst(int i, double d) { 12 Link newLink = new Link(i, d); 13 if (isEmpty()) { 14 last = newLink; 15 } 16 newLink.setNext(first); 17 first = newLink; 18 } 19 20 //双端链表特性 21 public void insertLast(int i, double d) { 22 Link newLink = new Link(i, d); 23 if (isEmpty()) { 24 first = newLink; 25 } 26 else { 27 last.setNext(newLink); 28 } 29 last = newLink; 30 } 31 32 public Link deleteFirst() { 33 if (!isEmpty()) { 34 Link l = first; 35 first = first.getNext(); 36 if (isEmpty()) { 37 last = null; 38 } 39 return l; 40 } 41 return null; 42 } 43 44 public void displayList() { 45 Link current = first; 46 while (current != null) { 47 current.displayLink(); 48 current = current.getNext(); 49 } 50 } 51 52 }
1 public static void main(String[] args) { 2 FirstLastLinkList fll = new FirstLastLinkList(); 3 4 fll.insertLast(9, 9.2); 5 fll.insertFirst(1, 1.2); 6 fll.insertFirst(2, 2.2); 7 fll.insertLast(10, 10.2); 8 System.out.println("------------DISPLAY"); 9 fll.displayList(); 10 System.out.println("------------DELETE"); 11 fll.deleteFirst().displayLink(); 12 System.out.println("------------DISPLAY"); 13 fll.displayList(); 14 15 }
打印结果:
------------DISPLAY
{ 2 , 2.2 }
{ 1 , 1.2 }
{ 9 , 9.2 }
{ 10 , 10.2 }
------------DELETE
{ 2 , 2.2 }
------------DISPLAY
{ 1 , 1.2 }
{ 9 , 9.2 }
{ 10 , 10.2 }