Implementing the data structure of queues and stacks by using arrays

Array array classes based on the previous article.

Implementation of Array Array Array Class

package com.soecode.lyf.datastruct.array;

/** Basic array of data structures
 * @author Wei Wen Si
 * @date 2019/8/30$ 14:23$
 */
public class Array<E> {

    private E[] data;
    //Assuming initial length
    private int size;


    public Array(int capcity) {
        data = (E[]) new Object[capcity];
        size = 0;
    }
    public Array() {
    }

    //Capture the capacity of an array
    public int getCapacity() {
        return data.length;
    }

    //Gets the number of elements in an array
    public int getSize() {
        return size;
    }

    // Whether the return array is empty
    public boolean isEmpty() {
        return size == 0;
    }

    //Adding new elements to the array specified index
    public void add(int index, E e) {
        if (size == data.length) {
          // Throw new Runtime Exception ("capacity exceeding limit");
            //Expansion of arrays
            resize(2 * data.length);
        }
        if (index < 0 || index > size) {
            throw new RuntimeException("Parameter input error");
        }
        for (int i = size - 1; i >= index; i--)
            //Move the data on the right side of index to the right, and then free up the space we need.
            data[i + 1] = data[i];
        //Store data in a specified location
        data[index] = e;
        size++;
    }
    // Remove the element in the index position from the array and return the deleted element
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; //Vacuum the last bit of data to prevent memory leaks

        if(size == data.length / 4 && data.length / 2 != 0)
            resize(data.length / 2);
        return ret;
    }

    // Delete the first element from the array and return the deleted element
    public E removeFirst(){
        return remove(0);
    }

    // Delete the last element from the array and return the deleted element
    public E removeLast(){
        return remove(size - 1);
    }
    //Append an element to the end of the array
    public void addLast(E e) {
        add(size, e);
    }

    //Get the element of index index index location
    public E get(int index) {
        if (index < 0 || index >= size)
            throw new RuntimeException("Array subscript error");
        return data[index];
    }

    //Modifying the elements of index number index
    public void update(int index, E e) {
        if (index < 0 || index >= size)
            throw new RuntimeException();
        data[index] = e;
    }
    // Find the index of the element e in the array, and return - 1 if there is no element e
    public int find(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i] == e)
                return i;
        }
        return -1;
    }
    //Get the last data of the array
    public E getLast(){
        return get(size - 1);
    }
    //Get the first data of the array
    public E getFirst(){
        return get(0);
    }
    // Find if there is an element e in the array
    public boolean contains(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i] == e)
                return true;
        }
        return false;
    }

    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append('[');
        for (int i = 0; i < size; i++) {
            res.append(data[i]);
            if (i != size - 1)
                res.append(", ");
        }
        res.append(']');
        return res.toString();
    }
    // Change the capacity of array space to the size of new Capacity
    private void resize(int newCapacity){
        E[] newData = (E[])new Object[newCapacity];
        for(int i = 0 ; i < size ; i ++)
            newData[i] = data[i];
        data = newData;
    }

   
}

Using Array to Realize Data Structure of Stack

Characteristics of stack

Linear storage structure, first in, last out, can only insert and delete operations on the top of the stack

package com.soecode.lyf.datastruct.array;

/**  Stack data structure based on array implementation
 * @author Wei Wen Si
 * @date 2019/8/30$ 16:08$
 */
public class ArrayStack <E>{

private   Array<E> array;

    public ArrayStack(int capacity){
        array = new Array<>(capacity);
    }

    //Get the length of the stack
    public int getSize(){
        return array.getSize();
    }
    //Determine whether the stack data is empty
    public boolean isEmpty(){
        return array.isEmpty();
    }
    //Get stack capacity
    public int getCapacity(){
        return array.getCapacity();
    }
    //Push
    public  void push (E e){
        array.addLast(e);
    }
    //Stack out
    public  E  pop(){
       return array.removeLast();
    }
    //Get data from the top of the stack
    public E peek(){
        return array.getLast();
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("Stack: ");
        res.append('[');
        for(int i = 0 ; i < array.getSize() ; i ++){
            res.append(array.get(i));
            if(i != array.getSize() - 1)
                res.append(", ");
        }
        res.append("] top");
        return res.toString();
    }
    public static void main(String[] args) {
        ArrayStack<String> stringArrayStack = new ArrayStack<>(5);
        stringArrayStack.push("a");
        stringArrayStack.push("b");
        stringArrayStack.push("c");
        stringArrayStack.push("d");
        stringArrayStack.push("e");
        stringArrayStack.push("f");
        stringArrayStack.push("g");
        stringArrayStack.push("h");
        stringArrayStack.push("i");
        stringArrayStack.push("j");
        System.out.println("============================All data in the stack");
        System.out.println(stringArrayStack.toString());
        System.out.println("============================Data stack");
        System.out.println(stringArrayStack.pop());
        System.out.println("============================Stack top data");
        System.out.println(stringArrayStack.peek());
    }
}

Now that the data is clear, the stack is easy to implement.

Entering the stack is equivalent to putting data at the end of the array, and can only be added from the back, leaving the stack is equivalent to removing the last bit of data of the array and can only be removed from the last displacement. The stack is implemented by defining two methods of deleting the last bit of data and adding the last bit of data.

Implementation of Simple Queue

Characteristics of queues

FIFO

Only delete operations are allowed at the front end and add operations at the end, which are linear structures like stacks.

Only the elements that first enter the queue can be deleted from the queue first, FIFO-first in first out.

The code is as follows:

package com.soecode.lyf.datastruct.array;

public class ArrayQueue<E>  {

    private Array<E> array;

    public ArrayQueue(int capacity){
        array = new Array<>(capacity);
    }

    public ArrayQueue(){
        array = new Array<>();
    }

    public int getSize(){
        return array.getSize();
    }

    public boolean isEmpty(){
        return array.isEmpty();
    }

    public int getCapacity(){
        return array.getCapacity();
    }

    /**
     * Join the team
     * @param e
     */
    public void enqueue(E e){
        array.addLast(e);
    }

    /**
     * Team out
     * @return
     */
    public E dequeue(){
        return array.removeFirst();
    }

    /**
     * Get the counterpart element
     * @return
     */
    public E getFront(){
        return array.getFirst();
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("Queue: ");
        res.append("front [");
        for(int i = 0 ; i < array.getSize() ; i ++){
            res.append(array.get(i));
            if(i != array.getSize() - 1)
                res.append(", ");
        }
        res.append("] tail");
        return res.toString();
    }

    public static void main(String[] args) {

        ArrayQueue<Integer> queue = new ArrayQueue<>(5  );
        for(int i = 0 ; i < 10 ; i ++){
            queue.enqueue(i);
            System.out.println(queue);
            if(i % 3 == 2){
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}

Entry: Add elements at the end of the data

Out: Remove the first element

The results are as follows:

Queue: front [0] tail
Queue: front [0, 1] tail
Queue: front [0, 1, 2] tail
Queue: front [1, 2] tail
Queue: front [1, 2, 3] tail
Queue: front [1, 2, 3, 4] tail
Queue: front [1, 2, 3, 4, 5] tail
Queue: front [2, 3, 4, 5] tail
Queue: front [2, 3, 4, 5, 6] tail
Queue: front [2, 3, 4, 5, 6, 7] tail
Queue: front [2, 3, 4, 5, 6, 7, 8] tail
Queue: front [3, 4, 5, 6, 7, 8] tail
Queue: front [3, 4, 5, 6, 7, 8, 9] tail

 

Posted by Zssz on Mon, 30 Sep 2019 12:03:18 -0700