什么是棧
稍微介紹一下關(guān)鍵名詞:
棧的應(yīng)用:
設(shè)計與介紹這里我們介紹數(shù)組實現(xiàn)的棧和鏈表實現(xiàn)的棧。 數(shù)組實現(xiàn) 結(jié)構(gòu)設(shè)計
private T data[];private int top;public seqStack() {data=(T[]) new Object[10];top=-1;}public seqStack(int maxsize){data=(T[]) new Object[maxsize];top=-1;} push插入 棧的核心操作之一push:入棧操作。
pop彈出并返回首位
其他操作
鏈表實現(xiàn) 有數(shù)組實現(xiàn),鏈表當(dāng)然也能實現(xiàn)。對于棧的運算。大致可以分為兩種思路:
結(jié)構(gòu)設(shè)計 長話短說,短話不說。直接上代碼就懂。 鏈表的節(jié)點: static class node<T>{T data;node next;public node() {}public node(T value){this.data=value;}} 基本結(jié)構(gòu): public class lisStack <T>{int length;node<T> head;//頭節(jié)點public lisStack() {head=new node<>();length=0;}//其他方法} push插入 與單鏈表頭插入一致,如果不太了解請先看筆者隊線性表介紹的。 和數(shù)組形成的棧有個區(qū)別。就是理論上棧沒有大小限制(不突破內(nèi)存系統(tǒng)限制)。不需要考慮是否越界。
pop彈出 與單鏈表頭刪除一致,如果不太了解請先看筆者隊線性表介紹的。 和數(shù)組同樣需要判斷是否為空。
其他操作
實現(xiàn)代碼數(shù)組實現(xiàn) package 隊棧;public class seqStack<T> { private T data[]; private int top; public seqStack() { data=(T[]) new Object[10]; top=-1; } public seqStack(int maxsize) { data=(T[]) new Object[maxsize]; top=-1; } boolean isEmpty() { return top==-1; } int length() { return top+1; } boolean push(T value) throws Exception//壓入棧 { if(top+1>data.length-1) { throw new Exception('棧已滿'); } else { data[++top]=value; return true; } } T peek() throws Exception//返回棧頂元素不移除 { if(!isEmpty()) { return data[top]; } else { throw new Exception('棧為空'); } } T pop() throws Exception { if(isEmpty()) { throw new Exception('棧為空'); } else { return data[top--]; } } public String toString() { if(top==-1) { return ''; } else { String va=''; for(int i=top;i>=0;i--) { va+=data[i]+' '; } return va; } }} 鏈表實現(xiàn) package 隊棧;public class lisStack <T>{ static class node<T> { T data; node next; public node() { } public node(T value) { this.data=value; } } int length; node<T> head;//頭節(jié)點 public lisStack() { head=new node<>(); length=0; } boolean isEmpty() { return head.next==null; } int length() { return length; } public void push(T value) {//近棧 node<T> team=new node<T>(value); if(length==0) { head.next=team; } else { team.next=head.next; head.next=team;} length++; } public T peek() throws Exception { if(length==0) {throw new Exception('鏈表為空');} else {//刪除 return (T) head.next.data; } } public T pop() throws Exception {//出棧 if(length==0) {throw new Exception('鏈表為空');} else {//刪除 T value=(T) head.next.data; head.next=head.next.next;//va.next length--; return value; } } public String toString(){ if(length==0) {return '';} else { String va=''; node team=head.next; while(team!=null) { va+=team.data+' '; team=team.next; } return va; } }} 測試 總結(jié)
|
|
來自: 星光閃亮圖書館 > 《數(shù)學(xué)》