list.java

来自「Java程序设计技巧与开发实例附书源代码。」· Java 代码 · 共 134 行

JAVA
134
字号

public class List
{
    private Node current;
    private Node start;
    public List()
    {
        start = current = null;
    }

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

    public boolean isLast()
    {
        if (current != null)
        {
            return (current.next == null);
        }
        else
        {
            return false;
        }
    }

    public void first() throws ListException
    {
        if (start == null)
        {
            throw new ListException("no first in empty list");
        }
        else
        {
            current = start;
        }
    }

    public void next() throws ListException
    {
        if (start == null)
        {
            throw new ListException("finding next in empty list");
        }
        else if (current.next == null)
        {
            throw new ListException("no next element available");
        }
        else
        {
            current = current.next;
        }
    }

    public Object retrieve() throws ListException
    {
        if (start == null)
        {
            throw new ListException("retrieving data from empty list");
        }
        else
        {
            return current.data;
        }
    }

    public void replace(Object obj) throws ListException
    {
        if (start == null)
        {
            throw new ListException("replacing data in empty list");
        }
        else
        {
            current.data = obj;
        }
    }

    public void remove() throws ListException
    {
        if (start == null)
        {
            throw new ListException("removing from empty list");
        }
        else if (current == start)
        {
            start = current = current.next;
        }
        else
        {
            Node prior = findPrevious(current);
            prior.next = current.next;
            current = current.next;
        }
        if (current == null)
        {
            current = start;
        }
    }

    public void insert(Object obj)
    {
        Node node = new Node(obj);
        if (current != null)
        {
            node.next = current.next;
            current.next = node;
        }
        else
        {
            start = node;
        }
        current = node;
    }

    private Node findPrevious(Node now) throws ListException
    {
        if (now == start)
        {
            throw new ListException("no previous element");
        }
        else
        {
            Node cursor = start;
            while (cursor.next != now)
            {
                cursor = cursor.next;
            }
            return cursor;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?