java实现线性表顺序查找
时间: 2025-03-06 08:01:41 浏览: 40
### Java 实现线性表顺序查找算法
在Java中,针对不同类型的线性表(如`ArrayList`或自定义的链表),可以实现顺序查找算法。下面分别展示基于数组列表和链表这两种常见线性表结构下的顺序查找方法。
#### 基于 ArrayList 的顺序查找
由于`ArrayList`内部是以数组形式存储元素,在这种情况下执行顺序查找非常直观:
```java
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayLinearSearch {
public static boolean sequentialSearch(ArrayList<Integer> list, int target){
for (Integer element : list) {
if(element.equals(target)){
return true;
}
}
return false;
}
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9, 11, 13, 15));
System.out.println("Is 7 present? " + sequentialSearch(numbers, 7)); // 输出: Is 7 present? true
System.out.println("Is 8 present? " + sequentialSearch(numbers, 8)); // 输出: Is 8 present? false
}
}
```
此代码片段展示了如何创建一个整数型的`ArrayList`并对其进行顺序查找[^1]。
#### 自定义单向链表上的顺序查找
当处理由节点组成的链表时,则需逐个访问每个节点直到找到目标值为止:
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedListSequentialSearch {
private Node head;
public LinkedListSequentialSearch() {
head = null;
}
/**
* 向链表尾部添加新节点.
*/
public void addLast(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
/**
* 对链表进行顺序查找.
*/
public boolean search(int key) {
Node temp = head;
while (temp != null && !temp.data.equals(key)) {
temp = temp.next;
}
return temp != null;
}
public static void main(String[] args) {
LinkedListSequentialSearch linkedList = new LinkedListSequentialSearch();
linkedList.addLast(1);
linkedList.addLast(3);
linkedList.addLast(5);
System.out.println("Does the list contain '3'? " + linkedList.search(3)); // 应该返回true
System.out.println("Does the list contain '4'? " + linkedList.search(4)); // 应该返回false
}
}
```
这段程序首先构建了一个简单的单项链表类及其基本功能——添加元素到链表末端以及按照给定键值进行顺序查找的功能[^5]。
阅读全文
相关推荐


















