Write a program to search a given element in the linked list.
Example 1:
Input: 5->2->8->4->1->NULL , target=8
Output: Element is found
Example 2:
Input: 5->2->8->4->1->NULL , target=10
Output: Element is not found
Approach
Java
public class LinkListSearchElement {public static void main(String[] args) {ListNode l = new ListNode(5);l.next = new ListNode(2);l.next.next = new ListNode(8);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(1);int value = 8;if (searchGivenNode(l, value)) {System.out.println("Element is found");} else {System.out.println("Element is not found");}}private static boolean searchGivenNode(ListNode head, int value) {while (head != null) {if (head.val == value) {return true;}head = head.next;}return false;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}// Time Complexity : O(n)
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to check the given//node is present in linked listbool searchElement(Node *head,int target){//if linked list is empty//return -1if(head==NULL)return false;//node to store the head of//the linked listNode *temp=head;//iterate till end of list or//count becomes nwhile(temp!=NULL){//if current node data//is same as the target value//the return trueif(temp->data==target)return true;//move to the next nodeelsetemp=temp->next;}//if element is not found//in linked list return falsereturn false;}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);int target=8;if(searchElement(head,target))cout<<"Element is found\n";elsecout<<"Element is not found\n";return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment