package aa.bb.cc.demo;
import java.util.Stack;
/**
* Stack的模擬(數組)
* @author 州偉
* @note 用數組模擬一個棧,注意數組是沒有變化的,不會刪除數組節點,主要是利用top值的變化來實現stack
*/
public class MyStack {
//Stack底層是一個數組(當然也可以list vector等,主要看是否要線程安全????)
private long[] arr;
private int top; //Stack頂
//默認構造方法
public MyStack(){
arr = new long[10];
top = -1;
}
//帶參數的構造方法
public MyStack(int maxSize){
arr = new long[maxSize];
top = -1;
}
//添加數據???
public void push(int value){
/**
* 這樣理解
* arr[top=top+1] = value;
*/
arr[++top] = value;
}
//移除一個數據???
public long pop(){
/**
* 沒有刪除的過程??????
*/
return arr[top--];
}
//查看數據???
public long peek(){
return arr[top];
}
//判斷是否爲空
public boolean isEmpty(){
return top == -1;
}
//判斷是否滿了
public boolean isFull(){
return top == arr.length -1;
}
/**
* main
* @param args
*/
public static void main(String[] args) {
MyStack ms = new MyStack(4);
ms.push(23);
ms.push(1);
ms.push(90);
ms.push(12);
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
System.out.println(ms.peek());
System.out.println(ms.peek());
System.out.println();
//先進後出,先出後進
while(!ms.isEmpty()){
System.out.println(ms.pop());
}
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
System.out.println("--------------自己模擬的stack與JDK中的Stack對比----------------");
//JDK中的Stack
Stack stack = new Stack();
stack.push(23);
stack.push(1);
stack.push(90);
stack.push(12);
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
System.out.println(stack.peek());
System.out.println();
//先進後出,先出後進
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
System.out.println(stack.isEmpty());
}
}
數據結構03.1->Stack棧的模擬(數組)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.