双端链表跟传统的单链表不同的地方是,单链表就只有一个first指向头结点的,而双端链表不仅有first指向头结点,而且有一个last指向尾结点。
代码展示:
public class Node { public int iNum; public double dNum; public Node next; //指向下一个结点 public Node(int i,double d){ iNum = i; dNum = d; } public void show(){ System.out.print("{"+iNum+","+dNum+"}"); } }
/** * 双端链表类:一个指向头节点,一个指向尾结点。插入和删除速度比较快, * @author link * */ public class FirstLastList { private Node first; private Node last; public FirstLastList(){ first = null; last = null; } public boolean isEmpty(){ return first == null; } /* * 前插入:判断链表是否为空,如果为空则把插入数据直接赋予给last,否则把插入节点的next指向 * 第一个数据(first),再把插入的数据变为头数据(first = link) */ public void insertFirst(int i,double d){ Node link = new Node(i,d); if(isEmpty()) last = link; else link.next = first; first = link; } /* * 尾插入:判断链表是否为空,如果为空则把插入数据直接赋予给first,否则尾部的next指向插入的数据。然后再 * 把数据变为最后一个(last = link)。 */ public void insertLast(int i,double d){ Node link = new Node(i,d); if(isEmpty()) first = link; else last.next = link; last = link; } public Node deleteFirst(){ Node temp = first; if(temp.next == null){ last = null; } first = first.next; return temp; } public void display(){ System.out.print("List(first-->last):"); Node current = first; while(current!=null){ current.show(); current = current.next; } System.out.println(); } }
public class FirstLastListApp { public static void main(String[] args) { FirstLastList list = new FirstLastList(); list.insertFirst(12, 2.3); list.insertFirst(42, 3.5); list.insertFirst(89, 12.2); list.insertFirst(41, 5.5); list.insertFirst(21, 2.8); list.insertFirst(43, 2.2); list.insertFirst(67, 6.9); list.display(); list.deleteFirst(); list.display(); list.insertLast(23, 3.5); list.insertLast(54, 4.5); list.display(); } }
测试结果:
List(first-->last):{67,6.9}{43,2.2}{21,2.8}{41,5.5}{89,12.2}{42,3.5}{12,2.3}
List(first-->last):{43,2.2}{21,2.8}{41,5.5}{89,12.2}{42,3.5}{12,2.3}
List(first-->last):{43,2.2}{21,2.8}{41,5.5}{89,12.2}{42,3.5}{12,2.3}{23,3.5}{54,4.5}
时间: 2024-10-07 04:43:30