Java在单链列表中搜索元素
在此程序中,我们需要在给定的单链列表中搜索节点。
身份矩阵
为解决此问题,我们将使用当前节点遍历该列表。当前指向头部并开始将搜索到的节点数据与当前节点数据进行比较。如果它们相等,则将标志设置为true,然后将消息连同搜索到的节点的位置一起打印。
例如,在上面的列表中,搜索节点说出4,可以在该位置找到4。
算法
创建一个具有两个属性的类Node: data和next。下一个是指向列表中下一个节点的指针。
创建另一个具有两个属性的类SearchLinkedList: head和tail。
addNode()将一个新节点添加到列表中: 创建一个新节点。 首先检查head是否等于null,这意味着列表为空。 如果列表为空,头和尾都将指向新添加的节点。 如果列表不为空,则新节点将被添加到列表的末尾,以使尾部的下一个指向新添加的节点。这个新节点将成为列表的新尾巴。
a.searchNode()将在列表中搜索节点:
变量i会跟踪搜索到的节点的位置。
变量标记将存储布尔值false。
节点当前将指向头节点。
通过将电流增加到current.next并将i增加到i +遍历循环
如果找到匹配项,则将每个节点的数据与搜索到的节点进行比较,将标志设置为true。
如果该标志为true,则显示搜索到的节点的位置。
否则,显示消息"列表中不存在元素"。
a.display()将显示列表中存在的节点:
定义一个当前将首先指向列表开头的节点。
遍历列表,直到当前指向null为止。
在每次迭代中通过使电流指向其旁边的节点来显示每个节点。
程序:
public class SearchLinkedList {
//Represent a node of the singly linked list
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
//Represent the head and tail of the singly linked list
public Node head = null;
public Node tail = null;
//addNode() will add a new node to the list
public void addNode(int data) {
//Create a new node
Node newNode = new Node(data);
//Checks if the list is empty
if(head == null) {
//if list is empty, both head and tail will point to new node
head = newNode;
tail = newNode;
}
else {
//newNode will be added after tail such that tails next will point to newNode
tail.next = newNode;
//newNode will become new tail of the list
tail = newNode;
}
}
//searchNode() will search for a given node in the list
public void searchNode(int data) {
Node current = head;
int i = 1;
boolean flag = false;
//Checks whether list is empty
if(head == null) {
System.out.println("List is empty");
}
else {
while(current != null) {
//Compares node to be found with each node present in the list
if(current.data == data) {
flag = true;
break;
}
i++;
current = current.next;
}
}
if(flag)
System.out.println("Element is present in the list at the position : " + i);
else
System.out.println("Element is not present in the list");
}
public static void main(String[] args) {
SearchLinkedList sList = new SearchLinkedList();
//Add nodes to the list
sList.addNode(1);
sList.addNode(2);
sList.addNode(3);
sList.addNode(4);
//Search for node 2 in the list
sList.searchNode(2);
//Search for a node in the list
sList.searchNode(7);
}
}
输出:
Element is present in the list at the position: 2
Element is not present in the list