Search an element in a Singly Linked List
Algorithm
- First check, If the head is null then simply return -1
- Create one variable position
- Create a new node current and node current will point to the head node
- Traverse Linked List from first to the last node
- Increase position value by one for each traversal
- Compare each node's data with the search value if current.data == value then return the position. Otherwise current = current.next
- Last, if the search value is not found then return 0
public int searchElement(int value) { if(head==null) { return -1; } int position = 0; Node current = head; while (current != null) { position++; if (current.data == value) { return position; } current = current.next; } return 0; }
Java Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | /*Node of a single linked list of integer */ public class SinglyLinkedList { private static Node head; /* instance variable */ private static class Node { private int data; /* we assume data integer */ private Node next; /* Create a node with the given data and next node */ public Node(int data) { this.data = data; this.next = null; } } /* Display the single linked list */ public void display() { Node current = head; while (current != null) { System.out.print(current.data + " --> "); current = current.next; } System.out.println("null"); } /* search element from single linked list */ public int searchElement(int value) { if(head==null) { return -1; } int position = 0; Node current = head; while (current != null) { position++; if (current.data == value) { return position; } current = current.next; } return 0; } public static void main(String[] args) { SinglyLinkedList s = new SinglyLinkedList(); s.head = new Node(10); Node second = new Node(7); Node third = new Node(20); Node fourth = new Node(80); s.head.next = second; // 10 --> 7 second.next = third; // 10 -->7 --> 20 third.next = fourth; // 10 -->7 --> 20 --> 8 -->null int a = s.searchElement(7); if(a==-1) { System.out.println("Empty List"); }else if(a==0) { System.out.println("Element not found"); } else { System.out.println("Element found at index " + a); } } } |
Output
Element found at index 2