Java中的棧
Java 集合框架提供了一個棧類,它實現了棧資料結構。棧實現 LIFO,即後進先出。這意味著最後壓入的元素是第一個彈出的元素。
以下是其中一些方法。
| 序號 | 方法及描述 |
|---|---|
| 1 | boolean empty() 測試此棧是否為空。如果棧為空,則返回 true;如果棧包含元素,則返回 false。 |
| 2 | Object peek( ) 返回棧頂的元素,但不將其移除。 |
| 3 | Object pop( ) 返回棧頂的元素,並將其移除。 |
| 4 | Object push(Object element) 將元素壓入棧中。同時返回該元素。 |
| 5 | int search(Object element) 在棧中搜索元素。如果找到,則返回其距棧頂的偏移量。否則,返回 -1。 |
下面給出了一個演示 Java 中棧的程式:
示例
import java.io.*;
import java.util.*;
public class Example {
public static void main (String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push(5);
s.push(1);
s.push(9);
s.push(4);
s.push(8);
System.out.print("The stack is: " + s);
System.out.print("
The element popped is: ");
Integer num1 = (Integer) s.pop();
System.out.print(num1);
System.out.print("
The stack after pop is: " + s);
Integer pos = (Integer) s.search(9);
if(pos == -1)
System.out.print("
The element 9 not found in stack");
else
System.out.print("
The element 9 is found at position " + pos + " in stack");
}
}輸出
The stack is: [5, 1, 9, 4, 8] The element popped is: 8 The stack after pop is: [5, 1, 9, 4] The element 9 is found at position 2 in stack
現在讓我們瞭解一下上面的程式。
五個元素被壓入棧中。然後顯示棧的內容。之後,棧頂元素被彈出並顯示。演示此操作的程式碼片段如下:
Stack<Integer> s = new Stack<Integer>();
s.push(5);
s.push(1);
s.push(9);
s.push(4);
s.push(8);
System.out.print("The stack is: " + s);
System.out.print("
The element popped is: ");
Integer num1 = (Integer) s.pop();
System.out.print(num1);
System.out.print("
The stack after pop is: " + s);之後,在棧中搜索元素 9。如果存在,則顯示其位置;否則,顯示該元素不在棧中。演示此操作的程式碼片段如下。
Integer pos = (Integer) s.search(9);
if(pos == -1)
System.out.print("
The element 9 not found in stack");
else
System.out.print("
The element 9 is found at position " + pos + " in stack");
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP