常用数据结构的详解(下)

来源:互联网 发布:vc源码 文件管理器 编辑:程序博客网 时间:2024/05/17 03:40
队列(Queue和Deque):
       队列是一种特殊的线性表,特殊之处在于它值允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。
       进行插入操作的端称为队尾,进行删除操作的端称为队头。


单向队列(Queue):先进先出(FIFO),只能从队列尾插入数据,只能从队列头删除数据。
双向队列(Deque):可以从队列尾/头插入数据,可以从队列头/尾删除数据。
       最擅长操作头和尾。

浏览一下ArrayDeque的一些源码(常用方法):


public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>,Cloneable, Serializable {transient Object[] elements; // non-private to simplify nested class accesstransient int head;transient int tail;private static final int MIN_INITIAL_CAPACITY = 8;private void allocateElements(int numElements) {int initialCapacity = MIN_INITIAL_CAPACITY;if (numElements >= initialCapacity) {initialCapacity = numElements;initialCapacity |= (initialCapacity >>> 1);initialCapacity |= (initialCapacity >>> 2);initialCapacity |= (initialCapacity >>> 4);initialCapacity |= (initialCapacity >>> 8);initialCapacity |= (initialCapacity >>> 16);initialCapacity++;if (initialCapacity < 0) // Too many elements, must back offinitialCapacity >>>= 1; // Good luck allocating 2^30 elements}elements = new Object[initialCapacity];}/** * Doubles the capacity of this deque. Call only when full, i.e., when head * and tail have wrapped around to become equal. */private void doubleCapacity() {assert head == tail;int p = head;int n = elements.length;int r = n - p; // number of elements to the right of pint newCapacity = n << 1;if (newCapacity < 0)throw new IllegalStateException("Sorry, deque too big");Object[] a = new Object[newCapacity];System.arraycopy(elements, p, a, 0, r);System.arraycopy(elements, 0, a, r, p);elements = a;head = 0;tail = n;}/** * 构造一个初始容量能够容纳 16 个元素的空数组双端队列。 */public ArrayDeque() {elements = new Object[16];}/** * 构造一个初始容量能够容纳指定数量的元素的空数组双端队列。 *  * @param numElements */public ArrayDeque(int numElements) {allocateElements(numElements);}/** * 构造一个包含指定 collection 的元素的双端队列,这些元素按 collection 的迭代器返回的顺序排列。 *  * @param c */public ArrayDeque(Collection<? extends E> c) {allocateElements(c.size());addAll(c);}/** * 将指定元素插入此双端队列的开头。 *  * @param e */public void addFirst(E e) {if (e == null)throw new NullPointerException();elements[head = (head - 1) & (elements.length - 1)] = e;if (head == tail)doubleCapacity();}/** * 将指定元素插入此双端队列的末尾。 *  * @param e */public void addLast(E e) {if (e == null)throw new NullPointerException();elements[tail] = e;if ((tail = (tail + 1) & (elements.length - 1)) == head)doubleCapacity();}/** * 将指定元素插入此双端队列的开头。 *  * @param e * @return */public boolean offerFirst(E e) {addFirst(e);return true;}/** * 将指定元素插入此双端队列的末尾。 *  * @param e * @return */public boolean offerLast(E e) {addLast(e);return true;}/** * 获取并移除此双端队列第一个元素。 *  * @return */public E removeFirst() {E x = pollFirst();if (x == null)throw new NoSuchElementException();return x;}/** * 获取并移除此双端队列的最后一个元素。 *  * @return */public E removeLast() {E x = pollLast();if (x == null)throw new NoSuchElementException();return x;}/** * 获取并移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。 *  * @return */public E pollFirst() {final Object[] elements = this.elements;final int h = head;@SuppressWarnings("unchecked")E result = (E) elements[h];// Element is null if deque emptyif (result != null) {elements[h] = null; // Must null out slothead = (h + 1) & (elements.length - 1);}return result;}/** * 获取并移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。 *  * @return */public E pollLast() {final Object[] elements = this.elements;final int t = (tail - 1) & (elements.length - 1);@SuppressWarnings("unchecked")E result = (E) elements[t];if (result != null) {elements[t] = null;tail = t;}return result;}/** * 获取,但不移除此双端队列的第一个元素。 *  * @return */public E getFirst() {@SuppressWarnings("unchecked")E result = (E) elements[head];if (result == null)throw new NoSuchElementException();return result;}/** * 获取,但不移除此双端队列的最后一个元素。 *  * @return */public E getLast() {@SuppressWarnings("unchecked")E result = (E) elements[(tail - 1) & (elements.length - 1)];if (result == null)throw new NoSuchElementException();return result;}/** * 获取,但不移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。 *  * @return */@SuppressWarnings("unchecked")public E peekFirst() {// elements[head] is null if deque emptyreturn (E) elements[head];}/** * 获取,但不移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。 *  * @return */@SuppressWarnings("unchecked")public E peekLast() {return (E) elements[(tail - 1) & (elements.length - 1)];}/** * 移除此双端队列中第一次出现的指定元素(当从头部到尾部遍历双端队列时)。 *  * @param o * @return */public boolean removeFirstOccurrence(Object o) {if (o != null) {int mask = elements.length - 1;int i = head;for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {if (o.equals(x)) {delete(i);return true;}}}return false;}/** * 移除此双端队列中最后一次出现的指定元素(当从头部到尾部遍历双端队列时)。 *  * @param o * @return */public boolean removeLastOccurrence(Object o) {if (o != null) {int mask = elements.length - 1;int i = (tail - 1) & mask;for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {if (o.equals(x)) {delete(i);return true;}}}return false;}/** * 将指定元素插入此双端队列的末尾。 *  * @param e * @return */public boolean add(E e) {addLast(e);return true;}/** * 将指定元素插入此双端队列的末尾。 *  * @param e * @return */public boolean offer(E e) {return offerLast(e);}/** * 获取并移除此双端队列所表示的队列的头。 *  * @return */public E remove() {return removeFirst();}/** * 获取并移除此双端队列所表示的队列的头(换句话说,此双端队列的第一个元素);如果此双端队列为空,则返回 null。 *  * @return */public E poll() {return pollFirst();}/** * 获取,但不移除此双端队列所表示的队列的头。 *  * @return */public E element() {return getFirst();}/** * 获取,但不移除此双端队列所表示的队列的头;如果此双端队列为空,则返回 null。 *  * @return */public E peek() {return peekFirst();}/** * 将元素推入此双端队列所表示的堆栈。 *  * @param e */public void push(E e) {addFirst(e);}/** * 从此双端队列所表示的堆栈中弹出一个元素。 *  * @return */public E pop() {return removeFirst();}private void checkInvariants() {assert elements[tail] == null;assert head == tail ? elements[head] == null: (elements[head] != null && elements[(tail - 1)& (elements.length - 1)] != null);assert elements[(head - 1) & (elements.length - 1)] == null;}boolean delete(int i) {checkInvariants();final Object[] elements = this.elements;final int mask = elements.length - 1;final int h = head;final int t = tail;final int front = (i - h) & mask;final int back = (t - i) & mask;// Invariant: head <= i < tail mod circularityif (front >= ((t - h) & mask))throw new ConcurrentModificationException();// Optimize for least element motionif (front < back) {if (h <= i) {System.arraycopy(elements, h, elements, h + 1, front);} else { // Wrap aroundSystem.arraycopy(elements, 0, elements, 1, i);elements[0] = elements[mask];System.arraycopy(elements, h, elements, h + 1, mask - h);}elements[h] = null;head = (h + 1) & mask;return false;} else {if (i < t) { // Copy the null tail as wellSystem.arraycopy(elements, i + 1, elements, i, back);tail = t - 1;} else { // Wrap aroundSystem.arraycopy(elements, i + 1, elements, i, mask - i);elements[mask] = elements[0];System.arraycopy(elements, 1, elements, 0, t);tail = (t - 1) & mask;}return true;}}/** * 返回此双端队列中的元素数。 *  * @return */public int size() {return (tail - head) & (elements.length - 1);}/** * 如果此双端队列未包含任何元素,则返回 true。 *  * @return */public boolean isEmpty() {return head == tail;}/** * 返回在此双端队列的元素上进行迭代的迭代器。 *  * @return */public Iterator<E> iterator() {return new DeqIterator();}/** * 返回以逆向顺序在此双端队列的元素上进行迭代的迭代器。 *  * @return */public Iterator<E> descendingIterator() {return new DescendingIterator();}private class DeqIterator implements Iterator<E> {private int cursor = head;private int fence = tail;private int lastRet = -1;public boolean hasNext() {return cursor != fence;}public E next() {if (cursor == fence)throw new NoSuchElementException();@SuppressWarnings("unchecked")E result = (E) elements[cursor];// This check doesn't catch all possible comodifications,// but does catch the ones that corrupt traversalif (tail != fence || result == null)throw new ConcurrentModificationException();lastRet = cursor;cursor = (cursor + 1) & (elements.length - 1);return result;}public void remove() {if (lastRet < 0)throw new IllegalStateException();if (delete(lastRet)) { // if left-shifted, undo increment in next()cursor = (cursor - 1) & (elements.length - 1);fence = tail;}lastRet = -1;}@Overridepublic void forEachRemaining(Consumer<? super E> action) {Objects.requireNonNull(action);Object[] a = elements;int m = a.length - 1, f = fence, i = cursor;cursor = f;while (i != f) {@SuppressWarnings("unchecked")E e = (E) a[i];i = (i + 1) & m;// Android-note: This uses a different heuristic for detecting// concurrent modification exceptions than next(). As such, this// is a less// precise test.if (e == null)throw new ConcurrentModificationException();action.accept(e);}}}private class DescendingIterator implements Iterator<E> {private int cursor = tail;private int fence = head;private int lastRet = -1;public boolean hasNext() {return cursor != fence;}public E next() {if (cursor == fence)throw new NoSuchElementException();cursor = (cursor - 1) & (elements.length - 1);@SuppressWarnings("unchecked")E result = (E) elements[cursor];if (head != fence || result == null)throw new ConcurrentModificationException();lastRet = cursor;return result;}public void remove() {if (lastRet < 0)throw new IllegalStateException();if (!delete(lastRet)) {cursor = (cursor + 1) & (elements.length - 1);fence = head;}lastRet = -1;}}/** * 如果此双端队列包含指定元素,则返回 true。 *  * @param o * @return */public boolean contains(Object o) {if (o != null) {int mask = elements.length - 1;int i = head;for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {if (o.equals(x))return true;}}return false;}/** * 从此双端队列中移除指定元素的单个实例。 *  * @param o * @return */public boolean remove(Object o) {return removeFirstOccurrence(o);}/** * 从此双端队列中移除所有元素。 */public void clear() {int h = head;int t = tail;if (h != t) { // clear all cellshead = tail = 0;int i = h;int mask = elements.length - 1;do {elements[i] = null;i = (i + 1) & mask;} while (i != t);}}/** * 返回一个以恰当顺序包含此双端队列所有元素的数组(从第一个元素到最后一个元素)。 *  * @return */public Object[] toArray() {final int head = this.head;final int tail = this.tail;boolean wrap = (tail < head);int end = wrap ? tail + elements.length : tail;Object[] a = Arrays.copyOfRange(elements, head, end);if (wrap)System.arraycopy(elements, 0, a, elements.length - head, tail);return a;}/** * 返回一个以恰当顺序包含此双端队列所有元素的数组(从第一个元素到最后一个元素);返回数组的运行时类型是指定数组的运行时类型。 *  * @param a * @return */@SuppressWarnings("unchecked")public <T> T[] toArray(T[] a) {final int head = this.head;final int tail = this.tail;boolean wrap = (tail < head);int size = (tail - head) + (wrap ? elements.length : 0);int firstLeg = size - (wrap ? tail : 0);int len = a.length;if (size > len) {a = (T[]) Arrays.copyOfRange(elements, head, head + size,a.getClass());} else {System.arraycopy(elements, head, a, 0, firstLeg);if (size < len)a[size] = null;}if (wrap)System.arraycopy(elements, 0, a, firstLeg, tail);return a;}/** * 返回此双端队列的副本。 *  * @return */public ArrayDeque<E> clone() {try {@SuppressWarnings("unchecked")ArrayDeque<E> result = (ArrayDeque<E>) super.clone();result.elements = Arrays.copyOf(elements, elements.length);return result;} catch (CloneNotSupportedException e) {throw new AssertionError();}}private static final long serialVersionUID = 2340985798034038923L;}




栈(Stack):又名堆栈,数据结构的一种,它是一种运算受限的线性表。存储特点:Last In First Out(后进先出)。
        Stack类表示后进先出(LIFO)的对象栈
其限制是仅允许在表的一端进行插入和删除运算。这一端称为栈顶,相对地,把另一端称为栈底。
新增:向一个栈插入新的元素又称作进栈,入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素。
删除:从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

基于数组来实现栈结构:
规定:最后一个位置是栈顶。
 索引为0的位置就是栈底。

要来实现栈的存储,底层可以数组来存储,也可以使用链表来存储。
Stack stack = new Stack();
官方建议使用:
ArrayDeque stack = new ArrayDeque();

ArrayDeque的源码在上面。




哈希表:
在一般的数组中,元素在数组中的索引位置是随机的,元素的取值和元素的位置之间不存在确定的关系,
因此在数组中查找特定的值时,需要把查找值和一系列的元素进行比较:
此时的查找效率依赖于查找过程中所进行的比较次数。

如果元素的值(value)和数组中的索引位置(index)有一个确定的对应关系(hash)。
公式为:index = hash(value);
那么对于给定的值,只要调用上述的hash(value)方法,就能找到数组中取值为value的元素的位置。



如果数组中元素的值和索引位置存在对应的关系,这样的数组就称之为哈希表,可以看出哈希表最大的优点就是
提供查找数据的效率。
一般情况下,我们是不会把哈希码(hashCode)作为元素在数组中的索引位置,因为哈希码很大,数组的长度有限,会造成索引越界的问题。
这个时候,我们可以在哈希码和元素位置之间做某种映射关系。

元素之-->hash(value)-->哈希码-->某种映射关系-->元素存储索引

注意:每个对象的哈希码是不同的。

哈希表的插入和查找是很优秀的;
可是当哈希表接近装满时,因为数组的扩容问题,性能较低(转移到更大的哈希表中)。


数组是会记录添加顺序的,按照索引位置来存储的,允许元素重复。
哈希表中:元素时不能重复的,对象如果相同则hashCode相同-->index相同
 不会记录元素添加的先后顺序。
原创粉丝点击