Java資料結構和演算法(四)——棧

來源:互聯網
上載者:User

標籤:stream   amp   ann   trace   []   next   turn   void   stack   

stack,中文翻譯為堆棧,事實上指的是棧,heap,堆。

這裡講的是資料結構的棧,不是記憶體配置裡面的堆和棧。


棧是先進後出的資料的結構,好比你碟子一個一個堆起來。最後放的那個是堆在最上面的。


隊列就是排隊買蘋果。先去的那個能夠先買。


public class Stack {    private int array[];    private int max;    private int top;    public Stack(int max){        this.max = max;        array = new int[max];        top = 0;    }    public void push(int value){        if(isFull()){            System.out.println("full,can not insert");            return;        }        array[top++]=value;    }    public int pop(){        return array[--top];    }    public boolean isEmpty(){        if(top == 0){            return true;        }        return false;    }    public boolean isFull(){        if(top == max ){            return true;        }        return false;    }    public void display(){        while(!isEmpty()){            System.out.println(pop());        }    }    public static void main(String[] args) {        Stack s = new Stack(5);        s.push(1);        s.push(3);        s.push(5);        s.push(5);        s.push(5);        s.display();    }}
事實上還是認為設定top為-1好計算一點。記住這裡的i++和++i,假設i=1,那麼array[i++]=2,指的是array[1]=2,下次用到i的時候i的值才會變2。而++i就是直接使用i=2。


top指向0,由於每次都push一個元素加一。那麼加入到最後一個元素的時候top=max。由於先進後出。那麼先出的是最後進的,剛剛為top-1所在的位置。

正確輸出:

55531

一、棧的使用——單詞逆序。

public String reverse(String in){        String out="";        for (int i = 0; i < in.length(); i++) {            char c = in.charAt(i);            push(c);        }        while(!isEmpty()){            out+=pop();        }        return out;    }    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        String string = s.nextLine();        Stack st = new Stack(string.length());        System.out.println(st.reverse(string));            }
將Stack的數群組類型改為char就可以。


讀取輸入也能夠用IO讀取。

    public static void main(String[] args) {        InputStreamReader is = new InputStreamReader(System.in);        BufferedReader b = new BufferedReader(is);        String string="";        try {            string = b.readLine();        } catch (IOException e) {            e.printStackTrace();        }        Stack st = new Stack(string.length());        System.out.println(st.reverse(string));    }


二、棧的使用——分隔字元匹配。

public int charat(char c){    for (int i = 0; i < array.length; i++) {        if(c == array[i])            return i;    }    return array.length;}public void match(String in){    String out="";    for (int i = 0; i < in.length(); i++) {        char c = in.charAt(i);        if(c == '{' || c == '(' || c == '[' ){            push(c);        }        if(c == '}' || c == ')' || c == ']'){            char temp = pop();            if(c == '}' && temp != '{'|| c == ')'  && temp != '('|| c == ']' && temp != ']'){                System.out.println("can not match in "+i);            }        }    }    while(!isEmpty()){        char c = pop();        if(c == '{'){            System.out.println("insert } to match "+charat(c));        }        if(c == '[' ){            System.out.println("insert ] to match "+charat(c));        }        if(c == '(' ){            System.out.println("insert ) to match "+charat(c));        }    }}public static void main(String[] args) {    Scanner s = new Scanner(System.in);    String string = s.nextLine();    Stack st = new Stack(string.length());    st.match(string);}result:klsjdf(klj{lkjjsdf{)can not match in 19insert } to match 1insert ) to match 0

將({[先壓入棧,一旦遇到)}]便與彈出的元素比較,若吻合。則匹配。假設一直沒有)}],最後便會彈出棧的左符號,提示是在詳細哪個位置,缺少的詳細的右符號類型。

這是能夠用棧來實現的工具。


棧中資料入棧和出棧的時間複雜度為常數O(1),由於與資料個數無關,直接壓入彈出。操作時間短。優勢便在這裡。假設現實生活的使用僅僅需用到先進後出的順序並且僅僅用到進出資料的比較,那就能夠使用棧了。

Java資料結構和演算法(四)——棧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.