数据结构学习笔记--栈结构

来源:互联网 发布:js正则匹配指定字符串 编辑:程序博客网 时间:2024/05/16 15:59

栈结构

基于数组的实现方式,代码如下:

public class StackApp {    public static class StackX{        private int maxSize;        private long[] stackArray;        private int top;        public StackX(int s){            maxSize = s;            stackArray = new long[maxSize];            top=-1;        }        public void push(long j){            stackArray[++top]=j;        }        public long pop(){            return stackArray[top--];        }        public long peek(){            return stackArray[top];        }        public boolean isEmpty(){            return (top==-1);        }        public boolean isFull(){            return (top==maxSize-1);        }    }    /**     * 栈的生成以及push和pop操作     */    public static void main(String[] args) {       StackX theStack = new StackX(10);       theStack.push(20);       theStack.push(40);       theStack.push(60);       theStack.push(80);       while(!theStack.isEmpty()){           long value = theStack.pop();           System.out.print(value);           System.out.print(" ");       }       System.out.println(" ");    }}* 栈的效率:  StackX类中实现的栈,数据项入栈和出栈的时间复杂度都为常数O(1)。这也就是说,栈操作所耗的时间不依赖于栈中数据项的个数,因此操作时间很短。栈不需要比较和移动操作。

以下是用链表的方式实现栈

class Node<E> {    Node<E> next = null;    E data;    public Node(E data) {        this.data = data;    }}public class Stack<E> {    Node<E> top = null;    public  boolean isEmpty() {        return top == null;    }    public void push(E data) {        Node<E> newNode = new Node<E>(data);        newNode.next = top;        top = newNode;    }    public E Pop() {        if (this.isEmpty()) {            return null;        }            E data = top.data;            top = top.next;            return data;        }    public E peek() {        if (isEmpty()) {            return null;        }        return top.data;    }}

栈实例1:单词逆序

将输入的单词逆序输出
代码如下:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class ReverseApp {    public static class Reverser {        private String input;        private String output;        public Reverser(String in) {            input = in;        }        public String doRev() {            int stackSize = input.length();            StackX theStack = new StackX(stackSize);            for (int j = 0; j < input.length(); j++) {                char ch = input.charAt(j);                theStack.push(ch);            }            output = "";            while (!theStack.isEmpty()) {                char ch = theStack.pop();                output = output + ch;            }            return output;        }    }    /**     * 栈实例1:单词逆序     * @throws IOException      */    public static void main(String[] args) throws IOException {        String input, output;        while(true){            System.out.println("Enter a string: ");            System.out.flush();//清空缓冲区            input = getString();            if(input.equals("")){                break;            }            Reverser theReverser = new Reverser(input);            output = theReverser.doRev();            System.out.println("Reversed:" + output);        }    }    public static String getString() throws IOException{        InputStreamReader isr = new InputStreamReader(System.in);//转换流,将字节流转换成字符流        BufferedReader br = new BufferedReader(isr);//将字符流包装成缓冲流        String s = br.readLine();        return s;    }    public static class StackX {        private int maxSize;        private char[] stackArray;        private int top;        public StackX(int s) {            maxSize = s;            stackArray = new char[maxSize];            top = -1;        }        public void push(char j) {            stackArray[++top] = j;        }        public char pop() {            return stackArray[top--];        }        public long peek() {            return stackArray[top];        }        public boolean isEmpty() {            return (top == -1);        }        public boolean isFull() {            return (top == maxSize - 1);        }    }}

运行结果如下:
这里写图片描述

栈实例2:分隔符匹配

  • 检查用户输入的一行文本中分隔符的程序。分隔符包括大括号“{}”和中括号“[]”和小括号“()”。每个做分隔符需要和右分隔符匹配:这就是说,每个‘{’后面要有‘}’来匹配,以此类推。
  • 分隔符匹配程序从字符串中不断地读取字符,每次读取一个字符。若发现他是左分隔符,将他压入栈中。当从输入中读到一个右分隔符时,弹出站定的左分隔符,并且查看它是否和右分隔符相匹配。如果不匹配(比如,一个左大括号和一个右小括号)则程序报错。如果栈中没有左分隔符和右分隔符匹配,或者已知存在没有被匹配的分隔符,程序也报错。分隔符没有被匹配。表现为把所有的字符读入之后栈中仍留有分隔符。
  • 这个方法的可行性在于,最后出现的左边分隔符需要最先匹配。这个规律符合栈的后进先出的特点。
  • 代码如下:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 栈实例2:分隔符匹配 */public class BracketApp {    public static class BracketChecker {        private String input;        public BracketChecker(String in) {            input = in;        }        public void check() {            int stackSize = input.length();            StackX theStack = new StackX(stackSize);            for (int j = 0; j < input.length(); j++) {                char ch = input.charAt(j);                switch (ch) {                case '{':                case '[':                case '(':                    theStack.push(ch);                    break;                case '}':                case ']':                case ')':                    if (!theStack.isEmpty()) {                        char chx = theStack.pop();                        if ((ch == '}' && chx != '{')                                || (ch == ']' && chx != '[')                                || (ch == ')' && chx != '(')) {                            System.out.println("Error:" + ch + "at" + j);                        }                    } else                        System.out.println("Error:" + ch + "at" + j);                    break;                default:                    break;                }            }            if (!theStack.isEmpty()) {                System.out.println("Error : missing right delimiter");            }        }    }    public static void main(String[] args) throws IOException {        String input;        while (true) {            System.out.println("Enter string contaning delimiter: ");            System.out.flush();// 清空缓冲区            input = getString();            if (input.equals("")) {                break;            }            BracketChecker bracketChecker = new BracketChecker(input);            bracketChecker.check();        }    }    public static String getString() throws IOException {        InputStreamReader isr = new InputStreamReader(System.in);// 转换流,将字节流转换成字符流        BufferedReader br = new BufferedReader(isr);// 将字符流包装成缓冲流        String s = br.readLine();        return s;    }    /**     * 栈代码     */    public static class StackX {        private int maxSize;        private char[] stackArray;        private int top;        public StackX(int s) {            maxSize = s;            stackArray = new char[maxSize];            top = -1;        }        public void push(char j) {            stackArray[++top] = j;        }        public char pop() {            return stackArray[top--];        }        public long peek() {            return stackArray[top];        }        public boolean isEmpty() {            return (top == -1);        }        public boolean isFull() {            return (top == maxSize - 1);        }    }}

运行结果如下
这里写图片描述

0 0
原创粉丝点击