数据结构-双端链表

/*
 * 文 件 名:  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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值