1 /*双端链表--比普通链表多了一个指向最后一个节点的引用
2 * 特点: 链表可以进行尾巴插入--输出顺序和输入顺序一致
3 * 但是不可以进行尾巴删除因为没有倒数第二节点的引用
4 * */
5 public class MyFirstAndLastLinkedList {
6 public Link first;
7 public Link last;
8
9 public MyFirstAndLastLinkedList() {
10 first = null;
11 last = null;
12 }
13
14 public boolean isEmpty(){
15 return first == null;
16 }
17
18 //头插入的时候注意空链表对last的处理
19 public void insertFirst(int key){
20 Link newLink = new Link(key);
21 if(isEmpty()){
22 last = newLink;
23 }
24 newLink.next = first;
25 first = newLink;
26 }
27
28 //尾插入的时候注意空链表对first的处理
29 public void insertLast(int key){
30 Link newLink = new Link(key);
31 if(isEmpty()){
32 first = newLink;
33 }
34 else{
35 last.next = newLink;
36 }
37 last = newLink;
38 }
39
40 //删除注意只有一个节点对last的处理
41 public Link deleteFirst(){
42 Link temp = first;
43 if(first.next == null){
44 last = null;
45 }
46 first = first.next;
47 return temp;
48 }
49
50 public void displayLinkedList(){//顺链打印
51 //System.out.println("first---to----last");
52 Link current = first;
53 while(current!= null ){
54 current.diaplayLink();
55 System.out.print("");
56 current = current.next;
57 }
58 System.out.println();
59 }
60
61 //测试该类
62 public static void main(String[] args) {
63 int[] arr = {1,2,3,4,5,6};
64 MyFirstAndLastLinkedList m = new MyFirstAndLastLinkedList();
65
66 for(int i = 0; i < arr.length; i++){
67 m.insertLast(arr[i]);
68 }
69 m.displayLinkedList();
70
71
72 }
73
74 }