本篇博文用java實現了數據結構中的順序棧和鏈棧
源碼分享在github:數據結構,當然你也可以從下面的代碼片中獲取
1.棧接口 IStack .java
public interface IStack {
public void clear();//置空
public boolean isEmpty();//判空
public int length(); //返回數據元素個數
public Object peek(); //取棧頂元素並返回其值
public void push(Object x)throws Exception; //將數據元素壓入棧頂
public Object pop(); //刪除並返回棧頂元素
}
2.順序棧 SqStack .java
public class SqStack implements IStack{
private Object[] stackElem;//對象數組
private int top;//在非空棧中,top始終指向棧頂元素的下一個存儲位置,當棧爲空時,top值爲0
//構造函數
public SqStack(int maxSize) {
top = 0;
stackElem = new Object[maxSize];//爲棧分配maxSize個存儲單元
}
//棧置空
@Override
public void clear() {
top = 0;
}
//判斷棧是否爲空
@Override
public boolean isEmpty() {
return top == 0;
}
//求棧中數據元素個數
@Override
public int length() {
return top;
}
//取棧頂元素
@Override
public Object peek() {
if(!isEmpty()){
return stackElem[top-1];
}else{
return null;
}
}
//入棧
@Override
public void push(Object x) throws Exception {
if(top == stackElem.length)//棧滿
throw new Exception("棧已滿");
else
stackElem[top++] = x;//先將X賦值給stackElem[top],再將top加一
}
//出棧
@Override
public Object pop() {
if(isEmpty())
return null;
else
return stackElem[--top];//先將top減一,再返回stackElem[top]的值
}
//輸出棧中所有元素(從棧頂到棧底元素)
public void display(){
for(int i = top-1;i>=0;i--){
System.out.print(stackElem[i].toString()+" ");//輸出
}
}
}
3.鏈棧 LinkStack.java
public class LinkStack implements IStack {
private Node top;//棧頂元素的引用
//將棧置空
@Override
public void clear() {
top = null;
}
//判斷棧是否爲空
@Override
public boolean isEmpty() {
return top==null;
}
//求棧的長度
@Override
public int length() {
Node p = top;
int length = 0;
while(p!=null){
p = p.next;
++length;
}
return length;
}
//取棧頂元素並返回其值
@Override
public Object peek() {
if(!isEmpty())
return top.data;
else
return null;
}
//入棧
@Override
public void push(Object x) throws Exception {
Node p = new Node(x);
p.next = top;
top = p;
}
//出棧
@Override
public Object pop() {
if(isEmpty()){
return null;
}else{
Node p = top;
top = top.next;
return p.data;
}
}
//輸出棧中所有數據元素(頂到底)
public void display(){
Node p = top;
while(p!=null){
System.out.print(p.data.toString()+" ");
p = p.next;//指針後移
}
}
}
4.節點類 Node.java
public class Node {
public Object data;//存放節點值
public Node next;//後繼節點的引用
//無參數時的構造函數
public Node(){
this(null,null);
}
//帶一個參數時的構造函數
public Node(Object data){
this(data,null);
}
//帶兩個參數的構造函數
public Node(Object data, Node next){
this.data = data;
this.next = next;
}
}
數據結構這個系列是我學習時做的筆記,會持續更新,詳見我的github(地址在文章開頭)或我的其他博文,感覺不錯的話,關注一下吧!