tonglin0325的个人主页

Java数据结构——双端链表

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class FirstLastList{
private Link first;
private Link last;

public FirstLastList() { //构造函数
this.first = null;
this.last = null;
}

public boolean isEmpty(){
return (first == null);
}

public void insertFirst(int id,double dd){ //从链表的头开始插入
Link newLink = new Link(id,dd);
if(isEmpty()){
last = newLink; //不用改变first
}
newLink.next = first;
first = newLink;
}

public void insertLast(int id,double dd){ //从链表的尾开始插入
Link newLink = new Link(id,dd);
if(isEmpty()){
first = newLink; //不用改变last
}else{
last.next = newLink; //在last后面添加新元素,并修改last的位置
}
last = newLink; //注意:只有一个元素的时候,插入要把last也赋为newLink
}

public Link deleteFirst(){
Link temp = first; //暂存first
if(first.next == null){ //如果只有一个元素,把last也赋为null
last = null;
}
first = first.next; //把next设为first
return temp; //返回原来的first
}

public void displayList(){
System.out.println("List(first-->last):");
Link current = first; //用于不断改变位置实现遍历
while(current != null){
current.displayLink();
current = current.next;
}
}

}

public class FirstLastList_demo {

public static void main(String[] args) {
// TODO 自动生成的方法存根
FirstLastList theList = new FirstLastList();
theList.insertFirst(11, 11.1);
theList.insertFirst(22, 22.2);
theList.insertFirst(33, 33.3);
theList.insertFirst(44, 44.4);
theList.insertFirst(55, 55.5);
theList.displayList();

theList.deleteFirst();
theList.deleteFirst();
theList.deleteFirst();
theList.displayList();

}

}