//=================================================
// File Name : FirstLastList_demo
//------------------------------------------------------------------------------
// Author : Common
//类名:FirstLastList
//属性:
//方法:
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;
}
}
}
//主类
//Function : FirstLastList_demo
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();
}
}