共計 1353 個字符,預(yù)計需要花費 4 分鐘才能閱讀完成。
以下是一個簡單的 Java 順序棧的實現(xiàn)代碼:
public class SeqStack<T> {private int maxSize; // 棧的最大容量
private int top; // 棧頂指針
private Object[] stackArray; // 存儲元素的數(shù)組
// 構(gòu)造方法
public SeqStack(int maxSize) {this.maxSize = maxSize;
this.top = -1; // 初始化棧頂指針為 -1
this.stackArray = new Object[maxSize];
}
// 入棧操作
public void push(T element) {if (isFull()) {throw new RuntimeException("Stack is full!");
}
stackArray[++top] = element;
}
// 出棧操作
public T pop() {if (isEmpty()) {throw new RuntimeException("Stack is empty!");
}
@SuppressWarnings("unchecked")
T element = (T) stackArray[top];
stackArray[top--] = null; // 將棧頂元素置為 null,便于垃圾回收
return element;
}
// 獲取棧頂元素
public T peek() {if (isEmpty()) {throw new RuntimeException("Stack is empty!");
}
@SuppressWarnings("unchecked")
T element = (T) stackArray[top];
return element;
}
// 判斷棧是否為空
public boolean isEmpty() {return top == -1;
}
// 判斷棧是否已滿
public boolean isFull() {return top == maxSize - 1;
}
// 獲取棧的大小(當(dāng)前元素個數(shù))
public int size() {return top + 1;
}
}
可以使用以下代碼測試順序棧的功能:
public class Main {public static void main(String[] args) {SeqStack<Integer> stack = new SeqStack<>(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(" 棧頂元素:" + stack.peek()); // 輸出:5
stack.pop();
stack.pop();
System.out.println(" 棧頂元素:" + stack.peek()); // 輸出:3
System.out.println(" 棧是否為空:" + stack.isEmpty()); // 輸出:false
System.out.println(" 棧的大小:" + stack.size()); // 輸出:3
}
}
運行結(jié)果為:
棧頂元素:5
棧頂元素:3
棧是否為空:false
棧的大小:3
這個代碼實現(xiàn)了一個簡單的順序棧,并提供了入棧、出棧、獲取棧頂元素、判斷棧是否為空、判斷棧是否已滿、獲取棧的大小等功能。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完