Search_LL(List, element, Start)
Here, List is a Linked list containing n elements, in which we have to search element. Start is a pointer which is containing the address of starting Node. SUCCESS=1 is a constant which will be returned on successful search and FAILURE=0 is a constant which will be returned on unsuccessful search. Ptr is a intermediate pointer which is used to traverse the list.
Step 1: [check, if list is empty]
If Start = null then
return FAILURE;
Step 2: Ptr = Start
Step 3: While Ptr < > null repeat step 4
Step 4: i) If Ptr -> Data = Element then
return SUCCESS;
ii) Ptr = Ptr->Next
Step 5: return FAILURE;
Step 6: End
Click here for Explanation
Consider a List displaying below, In this there are 4 nodes. Starting node
Start Containing the address of starting node i.e. 2002, and last node containing the null value. Suppose we have search an
element=45 in the list
|
List |
Since
Start is not null so step 2 will be executed next
Step 2:
Ptr=Start=2002 i.e Ptr is now also pointing to the starting node.
Step 3: [Iteration will be started]
Iteration 1:
Ptr->Data = 54 is not Equal to Element(=45).
so Ptr = Ptr->Next = 2044 [Now Ptr is pointing to next node]
Iteration 2:
Ptr->Data = 45 is Equal to Element(=45)
so Return Success;
Now Suppose we have to search an element=60:
Iteration 1:
Ptr->Data = 54 is not Equal to Element(=60).
so Ptr = Ptr->Next = 2044 [Now Ptr is pointing to next node]
Iteration 2:
Ptr->Data = 45 is not Equal to Element(=60).
so Ptr = Ptr->Next = 5260 [Now Ptr is pointing to next node]
Iteration 3:
Ptr->Data = 10 is not Equal to Element(=60).
so Ptr = Ptr->Next = 3254 [Now Ptr is pointing to next node]
Iteration 4:
Ptr->Data = 87 is not Equal to Element(=60).
so Ptr = Ptr->Next = null [Now Ptr is now null]
Since Ptr =null now so that Iteration will be finished and Search was failed so
return FAILURE;
No comments:
Post a Comment