java data structure-stack

Second, the stack

1. The definition of the stack:

  Stack又叫LIFO(后进先出)表 : It is a table that restricts insertion and deletion to only one position. This position is the end of the table, which is called the top of the stack.

2. The basic operation of the stack:
  • push(进栈)
  • pop(出栈)
    Code example
package demo.test;

public class MyStack {
    //栈的底层使用数组存储元素
    int[] elements;

    public MyStack() {
        elements = new int[0];
    }

    //压入元素
    public void push(int element) {
        int[] newArr = new int[elements.length+1];
        //把原数组元素复制到新数组中
        for(int i=0;i<elements.length;i++) {
            newArr[i] = elements[i];
        }
        //把添加的元素放到新数组中
        newArr[elements.length] = element;
        //替换
        elements = newArr;
    }

    //取出栈顶元素
    public int pop() {
        if (elements.length==0) {
            throw new RuntimeException("stack is empty");
        }
        int element = elements[elements.length-1];
        //创建新数组
        int[] newArr = new int[elements.length-1];
        //取出后放入新数组
        for (int i=0;i<elements.length-1;i++) {
            newArr[i] = elements[i];
        }
        //替换数组
        elements = newArr;
        //返回栈顶元素
        return element;
    }

    //查看栈顶元素
    public int peek() {
        if (elements.length==0) {
            throw new RuntimeException("stack is empty");
        }
        return elements[elements.length-1];
    }

    //判断栈顶元素是否为空
    public boolean isEmpty() {
        return elements.length == 0;
    }
}

Test code:

package demo.test1;

import demo.test.MyStack;

public class TestMyStack {
    public static void main(String[] args) {
        //创建一个栈
        MyStack ms = new MyStack();
        //压入数据
        ms.push(9);
        ms.push(8);
        ms.push(7);
        //取出栈顶元素
        System.out.println(ms.pop());
        System.out.println(ms.pop());
        System.out.println(ms.pop());
        //查看栈顶元素
        //System.out.println(ms.peek());
        System.out.println(ms.isEmpty());
    }
}
3. The realization of the stack:
  • Use chain structure
  • Use array
4. Stack application
 public static <AnyType> void printList(Iterator<AnyType> itr) {
            while(true) {
                if (!itr.hasNext())
                    return;
                System.out.println(itr.next());
            }
    }

Guess you like

Origin blog.csdn.net/Beer_xiaocai/article/details/87882932