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