資料結構複習之【棧】

來源:互聯網
上載者:User

棧:先進後出的線性表;

棧也可以通過順序儲存和鏈式儲存的方式實現;

一、順序儲存實現

 

數組的尾端作為棧頂;

代碼實現:

package org.xiazdong.list;public class MyArrayStack<T> {private static final int DEFAULT_LENGTH = 10;private T[]t;private int length;private int top;public MyArrayStack(){t = (T[])new Object[DEFAULT_LENGTH];length = 0;top = -1;}public void push(T e){if((top+1)>=t.length){larger(t.length*2);}top++;if(top>=t.length){}t[top]=e;}public T top(){return t[top];}public T pop(){if(top<0){throw new ArrayIndexOutOfBoundsException();}T tmp = t[top];top--;return tmp;}public int getSize(){return top+1;}private void larger(int len){T[]tmp = (T[])new Object[len];for(int i=0;i<t.length;i++){tmp[i] = t[i];}t = tmp;}}
二、鏈式儲存實現

 

鏈表的頭端作為棧頂;

代碼實現如下:

package org.xiazdong.list;import org.xiazdong.list.MyLinkedList.Node;public class MyLinkedStack <T>{private Node top;private int count;public MyLinkedStack(){count = 0;top = null;}public T pop(){if(top==null){throw new ArrayIndexOutOfBoundsException();}T elem = top.elem;top = top.next;return elem;}public T top(){return top.elem;}public void push(T e){Node n = new Node();n.elem = e;n.next = top;top = n;}class Node{private T elem;Node next;public Node(){elem = null;next = null;}public Node(T elem,Node next){this.elem = elem;this.next = next;}}}
三、比較

 

  順序儲存 鏈式儲存
優點 訪問快、增加刪除都為O(1) 增加刪除都為O(1),對於空間沒有限制
缺點 浪費空間,容易溢出 指標需要空間

 

四、棧的應用

 

1.遞迴

 

我們這裡以斐波那契數為例;fib(n) = fib(n-1)+fib(n-2),fib(2) = fib(1) = 1;

遞迴和棧是密不可分的,遞迴的實現就是通過棧來完成的;

 

2.尾碼運算式

 

我們在做計算機應用時肯定會用到尾碼運算式,中綴運算式轉換到尾碼運算式,尾碼運算式求出值都是通過棧實現的;

尾碼運算式的講解在:http://blog.csdn.net/xiazdong/article/details/7272693

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.