java实现stack search_Java Stack search()用法及代码示例

Java中的java.util.Stack.search(Object element)方法用于搜索堆栈中的元素并获取其与顶部的距离。此方法从1开始而不是从0开始计数位置。位于堆栈顶部的元素被视为在位置1。如果存在多个元素,则最接近顶部的元素的索引返回。如果成功找到该元素,则该方法返回其位置;如果缺少该元素,则返回-1。

用法:

STACK.search(element)

参数:该方法接受一个参数element ,该参数element 引用需要在堆栈中搜索的元素。

返回值:如果在堆栈中成功找到该元素,则该方法将返回该元素的位置(以计数为基数1),否则返回-1。

以下程序说明了java.util.Stack.search()方法的用法:

示例1:

// Java code to demonstrate search() method

import java.util.*;

public class Stack_Demo {

public static void main(String[] args)

{

// Creating an empty Stack

Stack STACK = new Stack();

// Stacking strings

STACK.push("Geeks");

STACK.push("4");

STACK.push("Geeks");

STACK.push("Welcomes");

STACK.push("You");

// Displaying the Stack

System.out.println("The stack is: " + STACK);

// Checking for the element "4"

System.out.println("Does the stack contains '4'? "

+ STACK.search("4"));

// Checking for the element "Hello"

System.out.println("Does the stack contains 'Hello'? "

+ STACK.search("Hello"));

// Checking for the element "Geeks"

System.out.println("Does the stack contains 'Geeks'? "

+ STACK.search("Geeks"));

}

}

输出:

The stack is: [Geeks, 4, Geeks, Welcomes, You]

Does the stack contains '4'? 4

Does the stack contains 'Hello'? -1

Does the stack contains 'Geeks'? 3

示例2:

// Java code to demonstrate search() method

import java.util.*;

public class Stack_Demo {

public static void main(String[] args)

{

// Creating an empty Stack

Stack STACK = new Stack();

// Stacking int values

STACK.push(8);

STACK.push(5);

STACK.push(9);

STACK.push(2);

STACK.push(4);

// Displaying the Stack

System.out.println("The stack is: " + STACK);

// Checking for the element 9

System.out.println("Does the stack contains '9'? "

+ STACK.search(9));

// Checking for the element 10

System.out.println("Does the stack contains '10'? "

+ STACK.search(10));

// Checking for the element 11

System.out.println("Does the stack contains '11'? "

+ STACK.search(11));

}

}

输出:

The stack is: [8, 5, 9, 2, 4]

Does the stack contains '9'? 3

Does the stack contains '10'? -1

Does the stack contains '11'? -1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值