"Algorithm" notes 1-- stacks and queues

  • Stack
  • queue
    • List implementation

      Stack

      The push (the stack) the latter is based on the last-set type (LIFO) policy. Here we are learning with both arrays and linked lists basic data structure to achieve stack.
      The basic operation of the stack supports are as push, pop.

      Variable-length arrays to achieve

      Use arrays implementing stacks, int type can declare a marker, the marker point is the position of the stack, when the push operation, the value of the position on the data tag while the tag + 1, pop, return array value of the flag position, while the mark 1.
      But an array of java in a statement at the time of its length has been fixed, so the space on the stack using only part of the maximum capacity of the array. In order to accommodate more data and declare an extremely large array can be very wasteful of space, then how to solve this problem, to waste neither an array of space beyond the range of the array does not it?
      When the size of the array may be employed to dynamically adjust the way, in the full stack push operation results, re-create an array that has a capacity twice that of the original array. Similarly when the array of free space pop operation to a certain extent, to re-create a smaller capacity of the array. But the criteria can not be idle half 1/2, otherwise it will cause occurs at a critical point in the push and pop operations 1/2 "jitter," that is frequently an array expansion, volume reduction operation, which greatly reduces stack performance. It is common practice when reduced to 1/4 of volume reduction of the capacity of the array is 1/2.

The variable length code for the following array:

public class StackResizeArray<Item>  {
    private Item[] a; // array of items
    private int n; // number of elements on stack

    public StackResizeArray() {
        a = (Item[]) new Object[2];
        n = 0;
    }

    public boolean isEmpty() {
        return n == 0;
    }

    public int size() {
        return n;
    }

    private void resize(int capacity) {
        assert capacity >= n;

        Item[] temp = (Item[]) new Object[capacity];
        for (int i = 0; i < n; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    public void push(Item item) {
        if (n == a.length)
            resize(2 * a.length); // double size of array if necessary
        a[n++] = item; // add item
    }

    public Item pop() {
        if (isEmpty())
            throw new NoSuchElementException("Stack underflow");
        Item item = a[n - 1];
        a[n - 1] = null; // to avoid loitering
        n--;
        // shrink size of array if necessary
        if (n > 0 && n == a.length / 4)
            resize(a.length / 2);
        return item;
    }
}

pop method, a [n - 1] = null position in the array has the stack set to null, the object is to avoid the free, otherwise the object is not already in this position while the stack, but also the array reference, resulting in GC it can not be recovered.

List implementation

Another stack implementation is the use of linked list data structure is a recursive, or it is empty, or points to a reference node, the node contains a reference to a generic element and the other pointing to the list .
Base nodes may be configured list:

private static class Node<Item> {
    public Item item;
    public Node next;
}

Wherein the generic item variable data storage, the same type of next Node variable is used to point to the next node. The head of the list as a stack, push equivalent elements inserted in the header, pop is to remove elements from the header.
code show as below:

public class StackLinkedList<Item> {
    private static class Node<Item> {
        public Item item;
        public Node next;
    }

    private Node<Item> first;
    private int N;

    private boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void push(Item item) {
        Node<Item> oldFirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldFirst;
        N++;
    }

    public Item pop() {
        if (isEmpty())
            throw new NoSuchElementException("Stack underflow");
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }
}
Comparison of arrays and linked lists

The difference between an array and a linked list determines the difference between the two stacks achieved:

  • The access mode, the array can be accessed sequentially or in random access, and the list only sequential access; 
  • Storage position, adjacent the array of logic elements are also adjacent on the physical storage locations, and is not necessarily linked list; 
  • Storage space, since the list with a pointer field, a large array of storage density is better; 
  • When searching by serial number, an array of random access, the time required is constant, but the list does not support random access time and data needed to scale linearly.
  • Value by the lookup, if the disordered arrays, linked lists, and arrays are time complexity of O (n), but when an ordered array, binary search can be used to reduced time complexity of O (logn);
  • Inserting or deleting, the array moving average of n / 2 elements, the chain can simply modify the pointer; 
  • Space allocation: Although variable length arrays can be expanded, but the need to move a large number of elements, resulting in reduced operating efficiency, and if there is no more memory space will result in contiguous memory chunk allocation failures; node list storage space only when needed application distribution, as long as there is memory space can be allocated, the operation more flexible and efficient;

queue

List implementation

FIFO queue (the queue) is a set of first-out type (FIFO) policy-based. Here only concerned with the realization of the queue list. Stack and achieve a similar list comprising the nodes with the generic variable and the next item the variables that store data, which is used to point to the next node. Except that the head of the list, the tail will be operated, enqueued (the enqueue), brought out from the other team (dequeue) from one end of the list of
codes:

public class Queue<Item> {
    private static class Node<Item> {
        public Item item;
        public Node next;
    }

    private Node<Item> first;
    private Node<Item> last;
    private int N;

    public void enqueue(Item item) {
        Node<Item> oldLast = last;
        last = new Node<Item>();
        last.item = item;
        if (isEmpty()) {
            first = last;
        } else {
            oldLast.next = last;
        }
        N++;
    }

    public Item dequeue() {
        if (isEmpty()) {
            return null;
        }
        Item result = first.item;
        first = first.next;
        if (isEmpty()) {
            last = null;
        }
        N--;
        return result;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }
}

Guess you like

Origin www.cnblogs.com/zhixin9001/p/11324858.html