栈、队列、符号表

栈是一种基于先进后出(FILO)的数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。

我们称数据进入到栈的动作为压栈,数据从栈中出去的动作为弹栈。

image-20210810092605437

代码实现:

public class Stack<T> implements Iterable<T>{
    //记录首结点
    private Node head;
    //栈中元素的个数
    private int N;

    private class Node{
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public Stack() {
        this.head = new Node(null,null);
        this.N=0;
    }

    //判断当前栈中元素个数是否为0
    public boolean isEmpty(){
        return N==0;
    }

    //获取栈中元素的个数
    public int size(){
        return N;
    }

    //把t元素压入栈
    public void push(T t){
        //找到首结点指向的第一个结点
        Node oldFirst = head.next;
        //创建新结点
        Node newNode = new Node(t, null);
        //让首结点指向新结点
        head.next = newNode;
        //让新结点指向原来的第一个结点
        newNode.next=oldFirst;
        //元素个数+1;
        N++;
    }

    //弹出栈顶元素
    public T pop(){
        //找到首结点指向的第一个结点
        Node oldFirst = head.next;
        if (oldFirst==null){
            return null;
        }
        //让首结点指向原来第一个结点的下一个结点
        head.next=oldFirst.next;
        //元素个数-1;
        N--;
        return oldFirst.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator<T>{
        private Node n;

        public SIterator(){
            this.n=head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }
}

括号匹配问题

给定一个字符串,里边可能包含"()"小括号和其他字符,请编写程序检查该字符串的中的小括号是否成对出现。

例如:

"(上海)(长安)":正确匹配

"(上海)(长安)":正确匹配

"上海(长安(北京)(深圳)南京)":正确匹配

"上海(长安))":错误匹配

分析:

1.创建一个栈用来存储左括号

2.从左往右遍历字符串,拿到每一个字符

3.判断该字符是不是左括号,如果是,放入栈中存储

4.判断该字符是不是右括号,如果不是,继续下一次循环

5.如果该字符是右括号,则从栈中弹出一个元素t;

6.判断元素t是否为null,如果不是,则证明有对应的左括号,如果不是,则证明没有对应的左括号

7.循环结束后,判断栈中还有没有剩余的左括号,如果有,则不匹配,如果没有,则匹配

代码实现:

public class BracketsMatchTest {
    public static void main(String[] args) {
        String str = "上海(长安)())";
        boolean match = isMatch(str);
        System.out.println(str+"中的括号是否匹配:"+match);
    }

    /**
     * 判断str中的括号是否匹配
     * @param str 括号组成的字符串
     * @return 如果匹配,返回true,如果不匹配,返回false
     */
    public static boolean isMatch(String str){
        //1.创建栈对象,用来存储左括号
        Stack<String> chars = new Stack<>();
        //2.从左往右遍历字符串
        for (int i = 0; i < str.length(); i++) {
            String currChar = str.charAt(i)+ "";

            //3.判断当前字符是否为左括号,如果是,则把字符放入到栈中
            if (currChar.equals("(")){
                chars.push(currChar);
            }else if(currChar.equals(")")){
                //4.继续判断当前字符是否是有括号,如果是,则从栈中弹出一个左括号,并判断弹出的结果是否为null,如果为null证明没有匹配的左括号,如果不为null,则证明有匹配的左括号
                String pop = chars.pop();
                if (pop==null){
                    return false;
                }
            }

        }
        //5.判断栈中还有没有剩余的左括号,如果有,则证明括号不匹配
        return chars.size() == 0;

    }
}

逆波兰表达式求值问题

逆波兰表达式求值问题是我们计算机中经常遇到的一类问题,要研究明白这个问题,首先我们得搞清楚什么是逆波兰表达式?要搞清楚逆波兰表达式,我们得从中缀表达式说起。

中缀表达式:

中缀表达式就是我们平常生活中使用的表达式,例如:1+3*2,2-(1+3)等等,中缀表达式的特点是:二元运算符总 是置于两个操作数中间。

中缀表达式是人们最喜欢的表达式方式,因为简单,易懂。但是对于计算机来说就不是这样了,因为中缀表达式的运算顺序不具有规律性。不同的运算符具有不同的优先级,如果计算机执行中缀表达式,需要解析表达式语义,做大量的优先级相关操作。

逆波兰表达式(后缀表达式):

逆波兰表达式是波兰逻辑学家J・卢卡西维兹(J・ Lukasewicz)于1929年首先提出的一种表达式的表示方法,后缀表 达式的特点:运算符总是放在跟它相关的操作数之后。

中缀表达式 逆波兰表达式
a+b ab+
a+(b-c) abc-+
a+(b-c)*d abc-d*+
a*(b-c)+d abc-*d+

解决思路:

image-20210820172743888

代码实现:

@Test
    public void test1(){
        String[] notation = {"3", "17", "15", "-", "*", "18", "6", "/", "+"};
        int result = calculate(notation);
        System.out.println(result);
    }

    private int calculate(String[] notation) {
        //1.定义一个栈,用来存储操作数
        Stack<Integer> stack = new Stack<>();
        //2.从左往右便利逆波兰表达式,得到每一个元素
        for (int i = 0; i < notation.length; i++) {
            String curr = notation[i];
            //3.判断当前元素是运算符还是操作数
            Integer o1;
            Integer o2;
            switch (curr) {
                //4.运算符,从栈中弹出两个操作数,完成运算并压入栈中
                case "+":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    stack.push(o2 + o1);
                    break;
                case "-":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    stack.push(o2 - o1);
                    break;
                case "*":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    stack.push(o2 * o1);
                    break;
                case "/":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    stack.push(o2 / o1);
                    break;
                default:
                    //5.操作数,把操作数放入到栈中
                    stack.push(Integer.valueOf(curr));
            }

        }

        //6.得到栈中最后一个元素,就是逆波兰表达式的结果
        return stack.pop();
    }

队列

队列是一种基于先进先出(FIFO)的数据结构,是一种只能在一端进行插入,在另一端进行删除操作的特殊线性表,它 按照先进先出的原则存储数据,先进入的数据,在读取数据时先读被读出来。

image-20210823090301850

代码实现:

public class Queue<T> implements Iterable<T>{
    //记录首结点
    private Node head;
    //记录最后一个结点
    private Node last;
    //记录队列中元素的个数
    private int N;


    private class Node{
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    public Queue() {
        this.head = new Node(null,null);
        this.last=null;
        this.N=0;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return N==0;
    }

    //返回队列中元素的个数
    public int size(){
        return N;
    }

    //向队列中插入元素t
    public void enqueue(T t){

        if (last==null){
            //当前尾结点last为null
            last= new Node(t,null);
            head.next=last;
        }else {
            //当前尾结点last不为null
            Node oldLast = last;
            last = new Node(t, null);
            oldLast.next=last;
        }

        //元素个数+1
        N++;
    }

    //从队列中拿出一个元素
    public T dequeue(){
        if (isEmpty()){
            return null;
        }

        Node oldFirst= head.next;
        head.next=oldFirst.next;
        N--;

        //因为出队列其实是在删除元素,因此如果队列中的元素被删除完了,需要重置last=null;

        if (isEmpty()){
            last=null;
        }
        return oldFirst.item;
    }


    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator<T>{
        private Node n;

        public QIterator(){
            this.n=head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }

}

测试:

    @Test
    public void test(){
        Queue<Integer> queue = new Queue<>();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);
        System.out.println(queue.dequeue());
        System.out.println("===================");
        for (Integer integer : queue) {
            System.out.println(integer);
        }
    }

符号表

符号表最主要的目的就是将一个键和一个值联系起来,符号表能够将存储的数据元素是一个键和一个值共同组成的 键值对数据,我们可以根据键来查找对应的值。

image-20210823091447472

符号表中,键具有唯一性。

代码实现:

public class SymbolTable<K, V>{

    protected Node head;

    protected int N;

    protected class Node {
        protected K k;

        protected V v;

        public Node next;

        public Node(K k, V v, Node next){
            this.k = k;
            this.v = v;
            this.next = next;
        }
    }

    public SymbolTable(){
        this.head = new Node(null, null, null);
        this.N = 0;
    }

    public int size(){
        return N;
    }

    public void put(K k, V v){
        Node n = head;

        while (n.next != null){
            n = n.next;
            if (n.k.equals(k)){
                n.v = v;
                return;
            }
        }

        Node newNode = new Node(k, v, null);
        newNode.next = head.next;
        head.next = newNode;
        N++;
    }

    public V remove(K k){
        Node n = head;

        while (n.next != null){
            if(n.next.k.equals(k)){
                V v = n.next.v;
                n.next = n.next.next;
                N--;
                return v;
            }
            n = n.next;
        }
        return null;
    }

    public V get(K k){
        Node n = head;
        while (n.next != null){
            if(n.next.k.equals(k)){
                return n.next.v;
            }
            n = n.next;
        }
        return null;
    }
    
    public Set<K> keySet(){
        Set<K> set = new HashSet<>();
        Node n = head;
        while (n.next != null){
            n = n.next;
            set.add(n.k);
        }
        return set;
    }
}

测试:

    @Test
    public void test(){
        SymbolTable<Integer, String> table = new SymbolTable<>();
        table.put(1, "a");
        table.put(2, "b");
        table.put(3, "c");
        table.put(1, "d");

        System.out.println(table.get(1));
        System.out.println(table.remove(1));
        System.out.println(table.get(1));
    }

image-20210823094427421

有序符号表

刚才实现的符号表,我们可以称之为无序符号表,因为在插入的时候,并没有考虑键值对的顺序,而在实际生活 中,有时候我们需要根据键的大小进行排序,插入数据时要考虑顺序,那么接下来我们就实现一下有序符号表。

public class SortedSymbolTable<K extends Comparable<K>, V> extends SymbolTable<K, V>{

    public void put(K k,V v){
        Node curr = head.next;
        Node pre = head;

        //找到新节点需要插入的位置
        while (curr != null && k.compareTo(curr.k) > 0){
            pre = curr;
            curr = curr.next;
        }

        if(curr != null && k.compareTo(curr.k) == 0){
            curr.v = v;
            return;
        }
        pre.next = new Node(k, v, curr);
        N++;
    }
}

测试:

    @Test
    public void test2(){
        SymbolTable<Integer, String> table  = new SortedSymbolTable<>();
        table.put(3, "a");
        table.put(1, "b");
        table.put(2, "c");
        table.put(1, "d");

        for (Integer i : table.keySet()) {
            System.out.println("k:v ===>"+i+":"+table.get(i));
        }
    }

image-20210823100752000

原文地址:https://www.cnblogs.com/wwjj4811/p/15174628.html