Given two linked lists, the task is to check whether the first list is present in 2nd list or not.
Input : list1 = 10->20 list2 = 5->10->20 Output : LIST FOUND Input : list1 = 1->2->3->4 list2 = 1->2->1->2->3->4 Output : LIST FOUND Input : list1 = 1->2->3->4 list2 = 1->2->2->1->2->3 Output : LIST NOT FOUND
1- Take first node of second list.
2- Start matching the first list from this first node.
3- If whole lists match return true.
4- Else break and take first list to the first node again.
5- And take second list to its second node.
6- Repeat these steps until any of linked lists becomes empty.
7- If first list becomes empty then list found else not.
Below is the implementation.
Time Complexity : O(m*n) where m is the number of nodes in second list and n in first.
Above code can be optimized by using extra space i.e. stores the list into two strings and apply KMP algorithm. Refer https://ide.geeksforgeeks.org/3fXUaV for implementation provided by Nishant Singh .
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Binary Search on Singly Linked List
- Interpolation search vs Binary search
- Why is Binary Search preferred over Ternary Search?
- Best First Search (Informed Search)
- Linear Search vs Binary Search
- Repeatedly search an element by doubling it after every successful search
- Meta Binary Search | One-Sided Binary Search
- Find whether an array is subset of another array | Added Method 3
- Sort an array according to the order defined by another array
- Check if a string is suffix of another
- Closest greater element for every array element from another array
- Maximum in an array that can make another array sorted
- Find the minimum number of rectangles left after inserting one into another
- Check if each element of an Array is the Sum of any two elements of another Array
- Minimize length of prefix of string S containing all characters of another string T
- Check if a string can be converted to another by swapping of adjacent characters of given type
- Lexicographically smallest and largest anagrams of a string containing another string as its substring
- Check if the given two matrices are mirror images of one another
- Minimize elements to be added to a given array such that it contains another given array as its subsequence
- Length of longest substring to be deleted to make a string equal to another string