一、分析
棧是限定僅在表的一端進行插入或刪除操作的線性表,對於棧來說,操作端稱為棧頂,另一端則稱為棧底,棧的修改是按照后進先出的原則進行的,因此又稱為后進先出的線性表。
鏈棧是指采用鏈式存儲結構實現的棧,通常用單鏈表來表示,在單鏈表表頭進行棧的操作。
一個標准的鏈棧具有如下的基本操作:
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(int input) { 2 InitStack initStack = new InitStack(input); 3 initStack.nextStack = this.nextStack; 4 this.nextStack = initStack; 5 }
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的實現,由於只定義了整數的數組,因此只能操作整數數據,但鏈棧的基本思想都已實現。
四、糾正
隔了一段時間又回來看代碼,猛地發現這段代碼其實還不夠完善。(⊙x⊙;)
將鏈棧的基本操作定義成了InitStack類的方法,實例化結點時,會使每個結點都擁有這些方法,然而其實只有頭結點需要這些方法,其他結點都不需要。
因此可以將InitStack類定義成頭節點類,而其他節點定義成頭節點的內部類,這樣,就只有頭節點可以操作其他節點。
由於要修改的地方太多,這里我就不修改了,放在這里提醒自己。(就是因為懶……(><))