VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-nodes-of-linked-list-at-given-indexes/

⇱ Print nodes of linked list at given indexes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print nodes of linked list at given indexes

Last Updated : 26 Aug, 2024

Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to print the second linked list's 1st, 2nd and 5th node's data.

Note: All the position (represented by each node of sorted linked list) will be exist in the unsorted linked list.

Examples

Input: head1 = 1->2->5, head2 = 1->8->7->6->2->9->10
Output : 1->8->2
Explanation: Elements in head1 are 1, 2 and 5. Therefore, print 1st, 2nd and 5th elements of l2,Which are 1, 8 and 2.

Input: head1 = 2->5, head2 = 7->5->3->2->8
Output: 5->8

[Naive Approach]: Using Nested Loops - O(n2) Time and O(1) Space:

The idea is to use two nested loops to traverse two linked lists. The outer loop traverses the first list, while the inner loop traverses the second list until a specific position is reached, printing the data at that position.

Step-by-step approach:

  • Initialize two pointers, current1 (for the first list) and current2 (for the second list).
  • Loop through current1 until it is nullptr.
    • For each node in the first list, use a nested loop to traverse the second list until reaching the position indicated by current1->data.
    • Print the data of the node at the current position in the second list.
    • Reset current2 to the head of the second list after each outer loop iteration.

Below is the implementation of the above approach:  


Output
5 8 

Time Complexity:O(n), To traverse the second linked list completely.
Auxiliary Space: O(1)

[Expected Approach]: Single-Pass List Traversal - O(m+n) Time and O(1) Space

The idea is to utilize the sorted order of the first list to traverse the second list more efficiently, reducing unnecessary comparisons by skipping irrelevant nodes.

Step-by-step approach:

  • Initialize two pointers: current1 for the first list and current2 for the second list.
  • For each node in the first list, retrieve its data as targetPos.
  • Traverse the second list to the position indicated by targetPos.
  • Print the data at that position if it exists.

Below is the implementation of the above approach: 


Output
5 8 

Time Complexity: O(m+n), At worst case we would traverse each nodes of both linked list
Auxiliary Space: O(1)


Comment
Article Tags:
Article Tags: