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 C++ 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 firstname.lastname@example.org. 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.
- Binary Search on Singly Linked List
- Search an element in a Linked List (Iterative and Recursive)
- Reverse a sublist of linked list
- Longest increasing sublist in a linked list
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Convert singly linked list into circular linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Difference between Singly linked list and Doubly linked list
- Merge a linked list into another linked list at alternate positions
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Length of longest palindrome list in a linked list using O(1) extra space
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Repeatedly search an element by doubling it after every successful search