- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 实用资源
- Java - 速查指南
- Java - 实用资源
如何在 Java 中搜索链表中的元素
问题描述
如何在链表中搜索一个元素?
解决方案
以下示例演示如何使用 linkedlistname.indexof(element) 获取元素的首个位置,以及 linkedlistname.Lastindexof(elementname) 获取链表中元素的最后位置,从而在链表中搜索一个元素。
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
lList.add("2");
System.out.println("First index of 2 is:"+
lList.indexOf("2"));
System.out.println("Last index of 2 is:"+
lList.lastIndexOf("2"));
}
}
结果
以上代码示例将生成以下结果。
First index of 2 is: 1 Last index of 2 is: 5
下面是另一个在链表中搜索元素的例子。
import java.util.LinkedList;
public class Demo {
public static void main(String args[]) {
LinkedList<Integer> linkedlist1 = new LinkedList<>();
linkedlist1.add(001);
linkedlist1.add(002);
linkedlist1.add(003);
linkedlist1.add(004);
linkedlist1.add(005);
linkedlist1.add(003);
System.out.println("First index of 004 is : " + linkedlist1.indexOf(004));
System.out.println("Last index of 004 is : " + linkedlist1.lastIndexOf(004));
}
}
结果
以上代码示例将生成以下结果。
First index of 004 is : 3 Last index of 004 is : 3
java_data_structure.htm
广告