数据结构(Java)——列表的实现

参考Java软件结构与数据结构 John Lewis Joseph chase 著 金名译

0.总体UML

总体类图架构UML

1.列表理解

  • 链表是一种实现策略,使用引用在对象之间创建链接。
  • 列表集合 是一种概念性的表示方法,其思想是使事物以线性列表的方式进行组织,就像栈和队列一样,列表也可以使用数组和链表来实现。列表集合没有内在的容量大小,它可以随着需要而增大。列表集合更一般化,可以在列表的中间和末端添加和删除元素。
  • 列表可以分为有序列表、无序列表、索引列表。
    • 有序列表,是基于列表中元素的某种特性的。列表基于某个关键值排序,对于已经添加到有序列表中的元素,只要给定了元素的关键值,同时列表已经定义了元素的所有关键值,那么它在列表中就有一个固定的位置。
    • 无序列表,各个元素的位置并不基于元素的任何内在特性,但是不要被名字误导, 无序列表中的元素是按照特殊顺序放置,只是这种顺序与元素本身无关,列表的使用者会决定列表的顺序。
    • 索引列表,与无序列表类似,索引列表的各个元素之间也不存在能够决定他们在列表中顺序的内在关系。列表的使用者决定了元素的顺序,不过,除此之外,其每个元素都能够从一个数字索引值得到引用,该索引值从列表的头开始从0连续增加直到列表末端。当列表发生改变,索引值就响应的调整以保持顺序和连续性。索引列表为他的元素维护一段连续的数字索引值。

2.列表ADT

ListADT.java

package ds.java.ch06.listImpl;

import java.util.Iterator;

/** 
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午2:27:35 
 * @description 
 *  注意这里是接口继承
 */
public interface ListADT<T> extends Iterable<T>{

    public T removeFirst();
    public T removeLast();
    public T remove(T element);
    public T first();
    public T last();
    public boolean contains(T target);
    public boolean isEmpty();
    public int size();
    public Iterator<T> iterator();
    public String toString();



}
package ds.java.ch06.listImpl;
/** 
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午3:30:27 
 * @description 有序列表接口
 */
public interface OrderedListADT<T> extends ListADT<T> {

    public void add(T element);
}
package ds.java.ch06.listImpl;

/**
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午3:31:10
 * @description 类说明
 */
public interface UnorderedListADT<T> extends Iterable<T> {
    public void addToFront(T element);

    public void addToRear(T element);

    public void addAfter(T element, T target);

}

3.数组实现

package ds.java.ch06.listImpl;

import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午3:38:31
 * @description 列表共有操作的抽象类的定义
 */
public abstract class ArrayList<T> implements Iterable<T>, ListADT<T> {

    private final static int DEFAULT_CAPACITY = 100;
    private final static int NOT_FOUND = -1;

    protected int rear;// 表示列表中的元素数目
    protected T[] list;// 表示列表
    protected int modCount;//

    /**
     * 无参构造函数的实现
     */
    public ArrayList() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * 带参数的构造函数
     * 
     * @param initialCapacity
     */
    public ArrayList(int initialCapacity) {
        rear = 0;
        list = (T[]) (new Object[initialCapacity]);
        modCount = 0;
    }

    public T romove(T elem) {
        T result;
        int index = find(elem);
        if (index == NOT_FOUND) {
            throw new ElementNotFoundException("ArrayList");
        }

        result = list[index];// 结果找到

        rear--;

        // 移动
        for (int i = index; i < rear; i++) {
            list[i] = list[i++];// 元素向前移动

        }
        list[rear] = null;// 最后一个置空
        modCount++;

        return result;

    }

    /**
     * 获取需要删除的元素的索引
     * 
     * @param elem
     * @return
     */
    private int find(T elem) {
        int scan = 0;
        int result = NOT_FOUND;

        if (!isEmpty())
            while (result == NOT_FOUND && scan < rear)
                if (elem.equals(list[scan]))
                    result = scan;
                else
                    scan++;

        return result;
    }

    /**
     * 盘算是否存在当前元素
     */
    public boolean contains(T target) {
        return (find(target) != NOT_FOUND);
    }

    public void remove() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public T removeFirst() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public T removeLast() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public T remove(T element) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public T first() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public T last() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Iterator<T> iterator() {
        return new ArrayListIterator();
    }

    /**
     * 集合内部的Iterator
     * ArrayListIterator iterator over the elements of an ArrayList.
     */
    private class ArrayListIterator implements Iterator<T> {
        int iteratorModCount;// 检查修改计数
        int current;

        /**
         * 构造函数
         */
        public ArrayListIterator() {
            iteratorModCount = modCount;// /初始化
            current = 0;
        }

        /**
         * 判定是否还有元素
         */
        public boolean hasNext() throws ConcurrentModificationException {
            // 不断检查当前的修改计数是否一致不变
            if (iteratorModCount != modCount)
                throw new ConcurrentModificationException();

            return (current < rear);
        }

        /**
         * 返回当前的元素
         */
        public T next() throws ConcurrentModificationException {
            if (!hasNext())
                throw new NoSuchElementException();

            current++;

            return list[current - 1];
        }

        /**
         * 当从列表中移除元素的时候会报异常
         */
        public void remove() throws UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

    }

    /**
     * 数组扩大容量 
     */
    protected void expandCapacity() {
        //数组复制扩容
        list = Arrays.copyOf(list, list.length * 2);
    }

}
package ds.java.ch06.listImpl;

/**
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午7:31:50
 * @description 数组实现的有序列表
 */
public class ArrayOrderedList<T> extends ArrayList<T> implements
        OrderedListADT<T> {

    public ArrayOrderedList() {
        super();
    }

    public ArrayOrderedList(int initialCapacity) {
        super(initialCapacity);
    }

    @Override
    public void add(T element) {
        if (!(element instanceof Comparable)) {
            throw new NonComparableElementException("OrderList");
        }
        // 可以比较的元素类型
        Comparable<T> comparableElement = (Comparable<T>) element;
        if (size() == list.length)
            expandCapacity();

        int scan = 0;

        // 找到插入位置
        while (scan < rear && comparableElement.compareTo(list[scan]) > 0)
            scan++;

        // 将元素依次后移
        for (int shift = rear; shift > scan; shift--)
            list[shift] = list[shift - 1];

        // 元素插入
        list[scan] = element;
        rear++;
        modCount++;
    }

}
package ds.java.ch06.listImpl;

/**
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午8:00:29
 * @description
 */
public class ArrayUnorderedList<T> extends ArrayList<T> implements
        UnorderedListADT<T> {

    public ArrayUnorderedList() {
        super();
    }

    public ArrayUnorderedList(int initialCapacity) {
        super(initialCapacity);
    }

    @Override
    public void addToFront(T element) {
        if (size() == list.length)
            expandCapacity();

        for (int shift = rear; shift > 0; shift--)
            list[shift] = list[shift - 1];
        list[0] = element;
        rear++;
        modCount++;

    }

    @Override
    public void addToRear(T element) {
        if (size() == list.length)
            expandCapacity();
        list[rear] = element;
        rear++;
        modCount++;

    }

    /**
     * 在某个元素后面添加元素
     */
    @Override
    public void addAfter(T element, T target) {

        //如果满了就要扩容
        if (size() == list.length)
            expandCapacity();

        int scan = 0;

        // 查找插入点
        while (scan < rear && !target.equals(list[scan]))
            scan++;

        if (scan == rear)
            throw new ElementNotFoundException("UnorderedList");

        scan++;

        // 元素后移
        for (int shift = rear; shift > scan; shift--)
            list[shift] = list[shift - 1];

        // 插入元素
        list[scan] = element;
        rear++;
        modCount++;

    }

}

4.链表实现


package ds.java.ch06.listImpl;

import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午8:12:14
 * @description 类说明
 */
public abstract class LinkedList<T> implements Iterable<T>, ListADT<T> {

    protected int count;
    protected LinearNode<T> head, tail;
    protected int modCount;

    /**
     * Creates an empty list.
     */
    public LinkedList() {
        count = 0;
        head = tail = null;
        modCount = 0;
    }

    @Override
    public T removeFirst() {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        LinearNode<T> current = head;// 当前的结点

        /**
         * 是否相等
         */
        if (size() == 1)
            head = tail = null;
        else
            head = current.getNext();//

        count--;
        modCount++;
        return current.getElement();
    }

    @Override
    public T removeLast() {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");
        boolean found = false;
        // 使用两个引用遍历
        LinearNode<T> previous = null;// 前一结点的设置
        LinearNode<T> current = head;// 当前的结点

        // 找最后的结点
        while (current != null && !found) {
            if (current.equals(tail)) {
                found = true;
            } else {
                previous = current;
                current = current.getNext();
            }
        }
        /**
         * 是否相等
         */
        if (size() == 1)
            head = tail = null;
        else {
            tail = previous;
            tail.setNext(null);
        }
        count--;
        modCount++;

        return current.getElement();
    }

    @Override
    public T remove(T targetElement) {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        boolean found = false;
        // 使用两个引用遍历
        LinearNode<T> previous = null;// 前一结点的设置
        LinearNode<T> current = head;// 当前的结点

        while (current != null && !found)
            if (targetElement.equals(current.getElement()))
                found = true;
            else {
                previous = current;
                current = current.getNext();
            }

        // 如果没有发现需要删除的结点
        if (!found)
            throw new ElementNotFoundException("LinkedList");

        if (size() == 1) // only one element in the list
            head = tail = null;
        else if (current.equals(head)) // target is at the head
            head = current.getNext();
        else if (current.equals(tail)) // target is at the tail
        {
            tail = previous;
            tail.setNext(null);
        } else
            // target is in the middle
            previous.setNext(current.getNext());

        count--;
        modCount++;

        return current.getElement();
    }

    @Override
    public T first() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public T last() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean contains(T target) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Iterator<T> iterator() {
        return new LinkedListIterator();
    }

    /**
     * 内部类 的实现iterator
     * 
     * @author MrLBZ
     * 
     */
    private class LinkedListIterator implements Iterator<T> {
        private int iteratorModCount; // the number of elements in the
        private LinearNode<T> current; // the current position

        /**
         * 构造函数
         */
        public LinkedListIterator() {
            current = head;
            iteratorModCount = modCount;
        }

        /**
         * 判定是否还有下一个结点
         */
        public boolean hasNext() throws ConcurrentModificationException {
            if (iteratorModCount != modCount)
                throw new ConcurrentModificationException();

            return (current != null);
        }

        /**
         * 返回元素
         */
        public T next() throws ConcurrentModificationException {
            if (!hasNext())
                throw new NoSuchElementException();

            T result = current.getElement();
            current = current.getNext();
            return result;
        }

        /**
         * 移除元素
         */
        public void remove() throws UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }
    }

}
package ds.java.ch06.listImpl;
/** 
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午9:05:09 
 * @description 类说明
 */
public class LinkedOrderedList<T> extends LinkedList<T> implements
        OrderedListADT<T> {

    @Override
    public void add(T element) {

    }

}
package ds.java.ch06.listImpl;
/** 
 * @author LbZhang
 * @version 创建时间:2015年11月17日 下午9:06:03 
 * @description 类说明
 */
public class LinkedUnorderedList<T> extends LinkedList<T> implements
        UnorderedListADT<T> {

    @Override
    public void addToFront(T element) {
        LinearNode<T> lt = new LinearNode<T>(element);
        lt.setNext(head);
        head = lt;
        count++;
        modCount++;

    }

    @Override
    public void addToRear(T element) {
        LinearNode<T> lt = new LinearNode<T>(element);
        lt.setNext(null);
        tail.setNext(lt);
        count++;
        modCount++;

    }

    @Override
    public void addAfter(T element, T target) {
        //参照前面完善

    }

}
posted @ 2015-11-17 14:01  snowwolf101  阅读(382)  评论(0编辑  收藏  举报