1. 程式人生 > >數據結構——Java實現鏈棧

數據結構——Java實現鏈棧

整數 div 是否為空 false The 結構 == 小結 push

一、分析

  棧是限定僅在表的一端進行插入或刪除操作的線性表,對於棧來說,操作端稱為棧頂,另一端則稱為棧底,棧的修改是按照後進先出的原則進行的,因此又稱為後進先出的線性表。

  鏈棧是指采用鏈式存儲結構實現的棧,通常用單鏈表來表示,在單鏈表表頭進行棧的操作。

  一個標準的鏈棧具有如下的基本操作:

    1、初始化鏈棧

    2、銷毀鏈棧

    3、清空鏈棧

    4、檢測鏈棧是否為空

    5、返回鏈棧中的元素個數

    6、返回鏈棧的棧頂元素,不修改棧指針

    7、向鏈棧頂壓入元素

    8、從鏈棧頂彈出元素

    9、從棧底到棧頂遍歷鏈棧

  在Java中,我們可以將鏈棧中的每個結點統一定義成一個類,類中包含有“元素值”和“下一地址”兩個屬性。鏈棧的基本操作即為類的方法,每壓入一個元素即生成一個結點對象。為了操作方便,我們附設一個頭結點,頭結點不存儲值,它保存的是鏈棧的地址。這樣,初始化鏈棧即生成頭結點,銷毀鏈棧即銷毀頭結點。

二、實現

1、定義類屬性和構造函數

 1 class InitStack{
 2     
 3     private int [] data = new int[1];    //存儲元素值
 4     
 5     private InitStack nextStack;       //存儲下一地址
 6     
 7     public InitStack() {            //用於生成頭結點
 8         this.data = null;
 9         this.nextStack = null;
10     }
11     
12
public InitStack(int data) {      //用於生成鏈棧結點 13 this.data[0] = data; 14 this.nextStack = null; 15 } 16 }

2、清空鏈棧

1 public void clearStack() {
2     this.nextStack = null;      //令頭結點的下一地址為空,鏈棧即被清空
3 }

3、檢測鏈棧是否為空

1 public boolean stackEmpty() {
2     if(this.nextStack == null
) {   //判斷頭結點的下一地址是否為空即可 3 return true; 4 } 5 return false; 6 }

4、返回鏈棧中的元素個數

 1 public int stackLength() {
 2 
 3     InitStack theStack = this.nextStack;    //獲取頭結點的下一地址即鏈棧的第一個結點
 4     int i = 0;                    //初始化計數器
 5 
 6     for (i = 0; theStack != null; i++) {    //循環判斷如不為空,則計數器加一
 7         theStack = theStack.nextStack;
 8     }
 9     return i;
10 }

5、返回鏈棧的棧頂元素,不修改棧指針

1 public int [] getTop() {
2 
3     if(this.nextStack == null) {      //判斷是否為空棧
4         return null;
5     }
6 
7     return this.nextStack.data;
8 }

6、向鏈棧頂壓入元素

1 public void push(InitStack initStack) {
2     initStack.nextStack = this.nextStack;
3     this.nextStack = initStack;
4 }

7、從鏈棧頂彈出元素

 1 public int [] pop() {
 2 
 3     if (this.nextStack == null) {            //判斷棧是否為空
 4         return null;
 5     }
 6 
 7     int [] i = this.nextStack.data;           //獲取棧頂元素值
 8     this.nextStack = this.nextStack.nextStack;    //刪除棧頂元素
 9     return i;
10 }

8、從棧底到棧頂遍歷鏈棧

 1 public String stackTraverse() {          //這裏通過輸出棧元素值來表示遍歷
 2 
 3     InitStack theStack = this.nextStack;
 4     String s = "";
 5 
 6     while(theStack != null) {           //循環遍歷棧
 7         s = theStack.data[0] + "、" + s;
 8         theStack = theStack.nextStack;
 9     }
10 
11     if(s.length() == 0) {             //如果未獲得值,則直接輸出空字符串
12         return s;
13     }
14     return s.substring(0,s.length() - 1);   //除去最後的頓號後返回字符串

三、小結

  以上就是鏈棧用Java的實現,由於只定義了整數的數組,因此只能操作整數數據,但鏈棧的基本思想都已實現。

數據結構——Java實現鏈棧