/*
* 文 件 名: FirstLastList.java
* 描 述: 双端链表
* 修改时间: 2012-11-21
*/
package linklist;
/**
* 双端链表
*/
public class FirstLastList
{
/**
* 首节点引用
*/
Link first;
/**
* 尾节点引用
*/
Link last;
/**
* <默认构造函数>
*/
public FirstLastList()
{
first = null;
last = null;
}
/**
* 判断链表是否为空
* @return
* @see [类、类#方法、类#成员]
*/
public boolean isEmpty()
{
return first == null;
}
/**
* 遍历链表
*/
public void displayList()
{
Link current = first;
while (current != null)
{
current.displayLink();
current = current.next;
}
}
/**
* 在首节点插入元素
* @see [类、类#方法、类#成员]
*/
public void insertFirst(int iData, double dData)
{
Link link = new Link(iData, dData);
if (isEmpty())
{
last = link;
}
link.next = first;
first = link;
}
/**
* 在尾节点插入元素
* @param iData
* @param dData
* @see [类、类#方法、类#成员]
*/
public void insertLast(int iData, double dData)
{
Link link = new Link(iData, dData);
if (isEmpty())
{
first = link;
}
else
{
last.next = link;
}
last = link;
}
/**
* 从首节点处删除元素
* @return
* @throws EmptyLinkListException
* @see [类、类#方法、类#成员]
*/
public Link deleteFirst()
throws EmptyLinkListException
{
if (isEmpty())
{
throw new EmptyLinkListException();
}
else
{
Link temp = first;
first = first.next;
//这里有一个问题,如果链表中只有一个节点,调用该方法后last仍然指向刚才删除的节点,可能导致内存泄露
//保险起见,手动置last为null
if (isEmpty())
{
last = null;
}
return temp;
}
}
/**
* 返回链表头元素
* @return
* @see [类、类#方法、类#成员]
*/
public Link getFirst()
{
return first;
}
/**
* 返回链表尾元素
* @return
* @see [类、类#方法、类#成员]
*/
public Link getLast()
{
return last;
}
}