Search In Linked List problem GFG

 Given a linked list of n nodes and a key, the task is to check if the key is present in the linked list or not.


Example:


Input: n = 4, key = 3

1->2->3->4

Output: true

Explanation: 3 is present in Linked List, so the function returns true.



//{ Driver Code Starts

// Initial Template for Java


import java.io.*;

import java.util.*;


class Node {

    int data;

    Node next;


    Node(int x) {

        data = x;

        next = null;

    }

}


class GFG {

    public static void main(String args[]) throws IOException {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while (t > 0) {

            int n = sc.nextInt();

            Node head = new Node(sc.nextInt());

            Node tail = head;

            for (int i = 0; i < n - 1; i++) {

                tail.next = new Node(sc.nextInt());

                tail = tail.next;

            }

            int key = sc.nextInt();

            Solution g = new Solution();

            boolean ans = g.searchKey(n, head, key);

            System.out.println(ans ? "true" : "false");

            // printList(head);

            t--;


            System.out.println("~");

        }

    }

}

// } Driver Code Ends



// User function Template for Java


/* Node of a linked list

  class Node {

   int data;

    Node next;

    Node(int d)  { data = d;  next = null; }

}

*/

class Solution {

    static boolean searchKey(int n, Node head, int key) {

        // Code here

       Node tail = head; // Start from head

        

        while (tail != null) { // Traverse the list

            if (tail.data == key) { // Check if value matches

                return true;

            }

            tail = tail.next; // Move to next node

        }

        

        return false; // If not found, return false

    }

}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence