📜  在Java中使用示例堆栈 lastIndexOf() 方法

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

在Java中使用示例堆栈 lastIndexOf() 方法

Java.util.Stack.lastIndexOf(Object element)方法用于检查和查找堆栈中特定元素的出现。如果元素存在于 Stack 中,则 lastIndexOf() 方法返回元素最后一次出现的索引,否则返回 -1。此方法用于查找堆栈中特定元素的最后一次出现。

句法:

Stack.lastIndexOf(Object element)

参数:参数元素的类型为堆栈。它指的是需要检查其最后一次出现的元素。

返回值:该方法返回栈中元素最后一次出现的位置。如果堆栈中不存在该元素,则该方法返回 -1。返回值是整数类型。

下面的程序说明了Java.util.Stack.lastIndexOf() 方法:

方案一:

// Java code to illustrate lastIndexOf()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // Use add() method to add elements in the Stack
        stack.add("Geeks");
        stack.add("for");
        stack.add("Geeks");
        stack.add("10");
        stack.add("20");
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // The last position of an element is returned
        System.out.println("Last occurrence of Geeks is at index: "
                           + stack.lastIndexOf("Geeks"));
        System.out.println("Last occurrence of 10 is at index: "
                           + stack.lastIndexOf("10"));
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3

方案二:

// Java code to illustrate lastIndexOf()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // Use add() method to add elements in the Stack
        stack.add(10);
        stack.add(22);
        stack.add(3);
        stack.add(10);
        stack.add(20);
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // The last position of an element is returned
        System.out.println("Last occurrence of 10 is at index: "
                           + stack.lastIndexOf(10));
        System.out.println("Last occurrence of 20 is at index: "
                           + stack.lastIndexOf(20));
    }
}
输出:
Stack: [10, 22, 3, 10, 20]
Last occurrence of 10 is at index: 3
Last occurrence of 20 is at index: 4