📜  实现堆栈 API 的Java程序

📅  最后修改于: 2022-05-13 01:54:32.051000             🧑  作者: Mango

实现堆栈 API 的Java程序

堆栈是一种线性数据结构,它遵循执行插入/删除操作的特定顺序。顺序是 LIFO(后进先出)或 FILO(先进后出)。 Stack 使用 push()函数将新元素插入 Stack 和 pop()函数以从堆栈中删除元素。堆栈中的插入和移除只允许在称为 Top 的一端。堆栈完全满时发生溢出状态,堆栈完全空时发生下溢状态。

例子:

Input:

    stack.push(1)
    stack.push(2)
    stack.pop()
    stack.peek()

Output:
2
2

句法:

public class Stack extends Vector

堆栈 API 实现

Serializable, Cloneable, Iterable, Collection, List, RandomAccess.

堆栈中的方法:

  1. empty() – 测试此堆栈是否为空。
  2. peek() – 查看此堆栈顶部的对象而不将其从堆栈中移除。
  3. pop() – 移除此堆栈顶部的对象并将该对象作为此函数的值返回。
  4. push(E item) – 将一个项目推到这个堆栈的顶部。
  5. int search(Object o) – 返回对象在此堆栈上的从 1 开始的位置。

下面是问题陈述的实现:

Java
// Java program to implement Stack API
import java.util.Stack;
 
public class StackImpl {
    private Stack stack;
 
    // Constructor to create empty Stack.
    public StackImpl() { stack = new Stack(); }
 
    // method to check if stack is empty or not.
    public boolean empty() { return stack.empty(); }
 
    // method to return topmost element of stack
    public E peek() { return stack.peek(); }
 
    // method to remove and return topmost element of stack
    public E pop() { return stack.pop(); }
 
    // method to push an element into the stack
    public E push(E item) { return stack.push(item); }
 
    // method to return the position of an object
    // in a stack(1-based position)
    public int search(Object o) { return stack.search(o); }
 
    public static void main(String args[])
    {
        StackImpl stack = new StackImpl();
        System.out.println("element pushed : "
                           + stack.push("one"));
        System.out.println("element pushed : "
                           + stack.push("two"));
        System.out.println("element pushed : "
                           + stack.push("three"));
        System.out.println("element pushed : "
                           + stack.push("four"));
        System.out.println("element pushed : "
                           + stack.push("five"));
        System.out.println("element poped : "
                           + stack.pop());
        System.out.println("element poped : "
                           + stack.pop());
        System.out.println("Element peek : "
                           + stack.peek());
        System.out.println("position of element three - "
                           + stack.search("three"));
        while (!stack.empty()) {
            System.out.println("element poped : "
                               + stack.pop());
        }
    }
}



输出
element pushed : one
element pushed : two
element pushed : three
element pushed : four
element pushed : five
element poped : five
element poped : four
Element peek : three
position of element three - 1
element poped : three
element poped : two
element poped : one