在這個(gè)實(shí)例中,我們將學(xué)習(xí)用Java實(shí)現(xiàn)堆棧數(shù)據(jù)結(jié)構(gòu)。
要了解此示例,請(qǐng)確保您首先訪問以下教程,
// Stack implementation in Java
class Stack {
//存儲(chǔ)堆棧元素
private int arr[];
//表示堆棧的頂部
private int top;
//堆棧的總?cè)萘? private int capacity;
//創(chuàng)建堆棧
Stack(int size) {
// 初始化數(shù)組
// 初始化堆棧變量
arr = new int[size];
capacity = size;
top = -1;
}
// 將元素推送到堆棧頂部
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
// 終止程序
System.exit(1);
}
//在堆棧頂部插入元素
System.out.println("插入 " + x);
arr[++top] = x;
}
//從堆棧頂部彈出元素
public int pop() {
//如果堆棧為空
//沒有要彈出的元素
if (isEmpty()) {
System.out.println("STACK EMPTY");
//終止程序
System.exit(1);
}
//從堆棧頂部彈出元素
return arr[top--];
}
//返回堆棧的大小
public int getSize() {
return top + 1;
}
// 檢查堆棧是否為空
public Boolean isEmpty() {
return top == -1;
}
// 檢查堆棧是否已滿
public Boolean isFull() {
return top == capacity - 1;
}
// 顯示堆棧的元素
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("堆棧: ");
stack.printStack();
//從堆棧中刪除元素
stack.pop();
System.out.println("\n在彈出之后");
stack.printStack();
}
}輸出結(jié)果
插入 1 插入 2 插入 3 堆棧: 1, 2, 3, 在彈出之后 1, 2,
在上面的示例中,我們已經(jīng)用Java實(shí)現(xiàn)了堆棧數(shù)據(jù)結(jié)構(gòu)。
Java提供了一個(gè)可用于實(shí)現(xiàn)堆棧的內(nèi)置類 Stack。
import java.util.Stack;
class Main {
public static void main(String[] args) {
//創(chuàng)建一個(gè)Stack類的對(duì)象
Stack<String> animals= new Stack<>();
//將元素推入堆棧頂部
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
//從堆棧頂部彈出元素
animals.pop();
System.out.println("彈出后 Stack: " + animals);
}
}輸出結(jié)果
Stack: [Dog, Horse, Cat] 彈出后 Stack: [Dog, Horse]
在上面的示例中,我們使用了Java的Stack類以實(shí)現(xiàn)堆棧。這里,
animals.push() - 將元素插入堆棧頂部
animals.pop() - 從堆棧頂部刪除元素
注意,我們<String>在創(chuàng)建堆棧時(shí)使用了尖括號(hào)。它表示堆棧是泛型類型。要了解有關(guān)泛型的更多信息,請(qǐng)?jiān)L問Java 泛型。