Linear table - stack (java implementation)

1. Restricted linear table

In data structures, stacks and queues are also linear lists, but their operations are subject to certain restrictions.

Second, the stack

A stack is a linear list - a restricted linear list where insertions and deletions are performed on the same end of the list. One end of the inserted and deleted elements is called the top of the stack, the other end is called the bottom of the stack, and the stack without any elements is called the empty stack. The characteristic of stack is last in first out (LIFO).


Third, the realization of the stack

A stack can be implemented with the help of a sequence list or a linked list. A stack implemented with a sequence list is called a sequential stack, and a stack implemented with a linked list is called a linked stack. Here we use the sequence table to implement the sequence stack. To implement the stack in the way of sequence table, we need to reuse the previous code. The reused code is divided into two ways, inheritance and aggregation, which are implemented by inheritance and aggregation respectively.


Inheritance method
If the inheritance method is implemented, the methods of the parent class will be exposed. For example, the stack only has methods such as push, pop, isEmpty, and peek. If it inherits MyArrayList, it will expose methods such as add, remove, set, indexOf, etc. in the parent class. Users call these methods. The method will destroy the structure of the stack. Personally, I like to implement it by aggregation.

public class MyArrayStack2<T> extends MyArrayList<T> {
    //调用父类的构造方法
    public MyArrayStack2()
    {
        super();
    }
    public boolean push(T data)//调用父类的add方法,在栈底插入元素
    {
        return super.add(0, data);
    }
    public T pop()//调用父类的remove方法,删除栈底元素
    {
        return super.remove(0);
    }
    public T peek()//调用父类的get方法,查看栈底元素
    {
        return super.get(0);
    }
    @Override
    public boolean isEmpty() {  //和父类的方法一样,其实没必要重写
        return super.isEmpty();
    }
}

Aggregation method

public class MyArrayStack<T> {
    MyArrayList<T> stack;   //聚合方式实现顺序栈,定义一个顺序表,用来存储数据
    public MyArrayStack()
    {
        stack = new MyArrayList<T>();//初始化顺序表
    }
    public boolean push(T data)//调用顺序表的add方法,在栈底插入元素
    {
        stack.add(0, data);
        return true;
    }
    public T pop()//调用顺序表的remove方法,删除栈底元素
    {
        return stack.remove(0);
    }
    public T peek()//调用顺序表的get方法,查看栈底元素
    {
        return stack.get(0);
    }
    public boolean isEmpty()//调用顺序表的isEmpty方法,判断栈是否为空
    {
        return stack.isEmpty();
    }
}

Fourth, the test

import static java.lang.System.*;
public class TestStack {
    public static void main(String[] args) {
        MyArrayStack<String> stack1 = new MyArrayStack<String>();
        MyArrayStack2<String> stack2 = new MyArrayStack2<String>();
        stack1.push("北京");
        stack1.push("我");
        stack1.push("爱");
        stack1.push("你");
        while(!stack1.isEmpty())
        {
            out.print(stack1.pop()+" ");
        }
        out.println();
        stack2.push("数据结构");
        stack2.push("操作系统");
        stack2.push("软件工程");
        stack2.push("计算机图形学");
        stack2.push("数据库原理");

        out.println("栈顶元素为:"+stack2.peek());
        stack2.add(5,"我是栈底元素"); //这里调用了父类的add方法,在栈底插入了元素,                                       
        while(!stack2.isEmpty())        //已经破坏了栈后进先出的原则
        {
            out.print(stack2.pop()+" ");
        }
        out.println();
    }
}

operation result:

你 爱 我 北京 
栈顶元素为:数据库原理
数据库原理 计算机图形学 软件工程 操作系统 数据结构 我是栈底元素 

In this way, we implement the stack with the help of the previous code. For the class MyArrayList used above, please refer to the following article: https://blog.csdn.net/YIXIANG0234/article/details/79901468

Five, the array implementation of the stack

In addition to the above-mentioned methods of using sequential lists and linked lists, the implementation method of stacks can also be implemented by arrays. However, the implementation of arrays is flawed, that is, the size of the stack must be known in advance, otherwise the created stack capacity may be unreasonable, that is Too large (wasting space) or too small (data overflow), so it is best to use a sequential list or a linked list.

public class ArrayStack<T> {
    private int top;    //指向栈底元素
    private int maxSize;//栈的容量
    private Object[] data;//存放数据的Object数组
    public ArrayStack(int size)//根据参数初始化栈
    {
        if(size>0)
            maxSize = size;//初始化栈的大小
        data = new Object[maxSize];
        top = -1;//栈指针开始指向-1,即没有元素
    }
    public ArrayStack()//默认栈大小为10
    {
        this(10);
    }
    public boolean push(T myData)
    {
        if(isFull())
            throw new RuntimeException("您的栈已满,无法再加入新元素");
        top++;  //栈指针向后移动
        data[top] = myData;//数组对应位置插入数据
        return true;
    }
    public boolean isFull()
    {
        return top >= maxSize-1?true:false;//top指针大于等于maxSize-1时即为栈满
    }
    public boolean isEmpty()
    {
        return top == -1;//栈指针等于-1是表示没有数据,即为栈空
    }
    @SuppressWarnings("unchecked")
    public T pop()
    {
        if(isEmpty())
            throw new RuntimeException("您的栈已空,无法获取栈顶元素");
        return (T) data[top--];//弹出栈顶元素,并移动栈顶指针
    }
    @SuppressWarnings("unchecked")
    public T peek()
    {
        if(isEmpty())
            throw new RuntimeException("您的栈已空,无法查看栈顶元素");
        return (T) data[top];
    }
}

Six, test

import static java.lang.System.out;

public class TestArrayStack {

    public static void main(String[] args) {
        ArrayStack<String> ss = new ArrayStack<String>(5);
        ss.push("Java");
        ss.push("C");
        ss.push("C++");
        ss.push("Python");
        ss.push("C#");
        //ss.push("JavaScript");
        while(!ss.isEmpty())
        {
            out.println(ss.pop());
        }
        out.println(ss.peek());
        //out.println(ss.pop());

    }

}

operation result:

C#
Python
C++
C
Java
Exception in thread "main" java.lang.RuntimeException: 您的栈已空,无法查看栈顶元素

It can be seen from the test program that the use of arrays can also simulate stack operations well, except for the disadvantage that the size cannot be dynamically expanded.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324408719&siteId=291194637