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:
C++
// C++ program to print second linked list
// according to data in the first linked list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to print the second list according
// to the positions referred by the 1st list
void printSecondList(Node* head1, Node* head2) {
Node* current1 = head1;
Node* current2 = head2;
// While first linked list is not null
while (current1 != nullptr) {
int i = 1;
// While second linked list is not equal
// to the data in the node of the first linked list
while (i < current1->data) {
// Keep incrementing second list
current2 = current2->next;
i++;
}
// Print the node at position in second list
// pointed by current element of first list
cout << current2->data << " ";
// Increment first linked list
current1 = current1->next;
// Set temp1 to the start of the second linked list
current2 = head2;
}
}
int main() {
// create 1st list: 2 -> 5
Node* head1 = new Node(2);
head1->next = new Node(5);
// create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
Node* head2 = new Node(4);
head2->next = new Node(5);
head2->next->next = new Node(6);
head2->next->next->next = new Node(7);
head2->next->next->next->next = new Node(8);
printSecondList(head1, head2);
return 0;
}
C
// C program to print second linked list
// according to data in the first linked list
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to print the second list according
// to the positions referred by the 1st list
void printSecondList(struct Node* head1, struct Node* head2) {
struct Node* current1 = head1;
struct Node* current2 = head2;
// While first linked list is not null
while (current1 != NULL) {
int i = 1;
// While second linked list is not equal
// to the data in the node of the first linked list
while (i < current1->data) {
// Keep incrementing second list
current2 = current2->next;
i++;
}
// Print the node at position in second list
// pointed by current element of first list
printf("%d ", current2->data);
// Increment first linked list
current1 = current1->next;
// Set temp1 to the start of the second linked list
current2 = head2;
}
}
struct Node *createNode(int data)
{
struct Node *newNode =
(struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main() {
// create 1st list: 2 -> 5
struct Node* head1 = createNode(2);
head1->next = createNode(5);
// create 2nd list
// 4 -> 5 -> 6 -> 7 -> 8
struct Node* head2 = createNode(4);
head2->next = createNode(5);
head2->next->next = createNode(6);
head2->next->next->next = createNode(7);
head2->next->next->next->next = createNode(8);
printSecondList(head1, head2);
return 0;
}
Java
// Java program to print second linked list
// according to data in the first linked list
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to print the second list according
// to the positions referred by the 1st list
static void printSecondList(Node head1, Node head2) {
Node current1 = head1;
Node current2 = head2;
// While first linked list is not null
while (current1 != null) {
int i = 1;
// While second linked list is not equal
// to the data in the node of the first linked list
while (i < current1.data) {
// Keep incrementing second list
current2 = current2.next;
i++;
}
// Print the node at position in second list
// pointed by current element of first list
System.out.print(current2.data + " ");
// Increment first linked list
current1 = current1.next;
// Set temp1 to the start of the second linked list
current2 = head2;
}
}
public static void main(String[] args) {
// create 1st list: 2 -> 5
Node head1 = new Node(2);
head1.next = new Node(5);
// create 2nd list
// 4 -> 5 -> 6 -> 7 -> 8
Node head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
printSecondList(head1, head2);
}
}
Python
# Python3 program to prsecond linked list
# according to data in the first linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to print the second list according
# to the positions referred by the 1st list
def print_second_list(head1, head2):
current1 = head1
current2 = head2
# While first linked list is not null
while current1 is not None:
i = 1
# While second linked list is not equal
# to the data in the node of the first linked list
while i < current1.data:
# Keep incrementing second list
current2 = current2.next
i += 1
# Print the node at position in second list
# pointed by current element of first list
print(current2.data, end=" ")
# Increment first linked list
current1 = current1.next
# Set temp1 to the start of the second linked list
current2 = head2
# create 1st list: 2 -> 5
head1 = Node(2)
head1.next = Node(5)
# create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
head2 = Node(4)
head2.next = Node(5)
head2.next.next = Node(6)
head2.next.next.next = Node(7)
head2.next.next.next.next = Node(8)
print_second_list(head1, head2)
C#
// C# program to print second linked list
// according to data in the first linked list
using System;
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to print the second list according
// to the positions referred by the 1st list
public static void PrintSecondList(Node head1, Node head2) {
Node current1 = head1;
Node current2 = head2;
// While first linked list is not null
while (current1 != null) {
int i = 1;
// While second linked list is not equal
// to the data in the node of the first linked list
while (i < current1.data) {
// Keep incrementing second list
current2 = current2.next;
i++;
}
// Print the node at position in second list
// pointed by current element of first list
Console.Write(current2.data + " ");
// Increment first linked list
current1 = current1.next;
// Set temp1 to the start of the second linked list
current2 = head2;
}
}
public static void Main(string[] args) {
// create 1st list: 2 -> 5
Node head1 = new Node(2);
head1.next = new Node(5);
// create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
Node head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
PrintSecondList(head1, head2);
}
}
JavaScript
// JavaScript program to print second linked list
// according to data in the first linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to print the second list according
// to the positions referred by the 1st list
function printSecondList(head1, head2) {
let current1 = head1;
let current2 = head2;
// While first linked list is not null
while (current1 !== null) {
let i = 1;
// While second linked list is not equal
// to the data in the node of the first linked list
while (i < current1.data) {
// Keep incrementing second list
current2 = current2.next;
i++;
}
// Print the node at position in second list
// pointed by current element of first list
console.log(current2.data);
// Increment first linked list
current1 = current1.next;
// Set temp1 to the start of the second linked list
current2 = head2;
}
}
// create 1st list: 2 -> 5
let head1 = new Node(2);
head1.next = new Node(5);
// create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
let head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
printSecondList(head1, head2);
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:
C++
// C++ program to print second linked list
// according to data in the first linked list
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int x){
data = x;
next = nullptr;
}
};
// Function to print the second list according
// to the positions referred by the 1st list
void printSecondList(Node *head1, Node *head2){
// Step 1: Traverse the second list with a pointer
Node *current2 = head2;
// Position index starts at 1
int currentPos = 1;
// Traverse the first linked list to get positions
Node *current1 = head1;
while (current1 != nullptr)
{
int targetPos = current1->data;
// Move the pointer in the second list to the target position
while (current2 != nullptr && currentPos < targetPos)
{
current2 = current2->next;
currentPos++;
}
// Print the node data if it matches the target position
if (current2 != nullptr && currentPos == targetPos)
cout << current2->data << " ";
// Move to the next node in the first list
current1 = current1->next;
}
cout << endl;
}
int main()
{
// create 1st list: 2 -> 5
Node *head1 = new Node(2);
head1->next = new Node(5);
// create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
Node *head2 = new Node(4);
head2->next = new Node(5);
head2->next->next = new Node(6);
head2->next->next->next = new Node(7);
head2->next->next->next->next = new Node(8);
printSecondList(head1, head2);
return 0;
}
C
// C program to print second linked list
// according to data in the first linked list
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
// Function to print elements of the second list based on positions
// from the first list
void printSecondList(struct Node *head1, struct Node *head2)
{
// Pointer to traverse the second list
struct Node *current2 = head2;
// Start position index at 1
int currentPos = 1;
// Pointer to traverse the first list
struct Node *current1 = head1;
while (current1 != NULL)
{
// Get the target position from the first list
int targetPos = current1->data;
// Move the pointer in the second list to the target position
while (current2 != NULL && currentPos < targetPos)
{
current2 = current2->next;
currentPos++;
}
// Print the node data if it matches the target position
if (current2 != NULL && currentPos == targetPos)
printf("%d ", current2->data);
// Move to the next node in the first list
current1 = current1->next;
}
printf("\n");
}
struct Node *createNode(int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main()
{
// Create 1st list: 2 -> 5
struct Node *head1 = createNode(2);
head1->next = createNode(5);
// Create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
struct Node *head2 = createNode(4);
head2->next = createNode(5);
head2->next->next = createNode(6);
head2->next->next->next = createNode(7);
head2->next->next->next->next = createNode(8);
printSecondList(head1, head2);
return 0;
}
Java
// Java program to print second linked list
// according to data in the first linked list
class Node {
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
class GfG {
// Function to print elements of the second list based
// on positions from the first list
static void printSecondList(Node head1, Node head2)
{
// Pointer to traverse the second list
Node current2 = head2;
// Start position index at 1
int currentPos = 1;
// Pointer to traverse the first list
Node current1 = head1;
while (current1 != null) {
// Get the target position from the first list
int targetPos = current1.data;
// Move the pointer in the second list to the
// target position
while (current2 != null
&& currentPos < targetPos) {
current2 = current2.next;
currentPos++;
}
// Print the node data if it matches the target
// position
if (current2 != null
&& currentPos == targetPos) {
System.out.print(current2.data + " ");
}
// Move to the next node in the first list
current1 = current1.next;
}
System.out.println();
}
public static void main(String[] args)
{
// Create 1st list: 2 -> 5
Node head1 = new Node(2);
head1.next = new Node(5);
// Create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
Node head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
printSecondList(head1, head2);
}
}
Python
# Python program to print second linked list
# according to data in the first linked list
class Node:
def __init__(self, x):
self.data = x
self.next = None
def print_second_list(head1, head2):
# Pointer to traverse the second list
current2 = head2
# Start position index at 1
current_pos = 1
# Pointer to traverse the first list
current1 = head1
while current1:
# Get the target position from the first list
target_pos = current1.data
# Move the pointer in the second list to the target position
while current2 and current_pos < target_pos:
current2 = current2.next
current_pos += 1
# Print the node data if it matches the target position
if current2 and current_pos == target_pos:
print(current2.data, end=" ")
# Move to the next node in the first list
current1 = current1.next
print()
# Create 1st list: 2 -> 5
head1 = Node(2)
head1.next = Node(5)
# Create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
head2 = Node(4)
head2.next = Node(5)
head2.next.next = Node(6)
head2.next.next.next = Node(7)
head2.next.next.next.next = Node(8)
print_second_list(head1, head2)
C#
using System;
class Node {
public int data;
public Node next;
public Node(int x){
data = x;
next = null;
}
}
class GfG{
// Function to print elements of the second list based
// on positions from the first list
static void PrintSecondList(Node head1, Node head2)
{
// Pointer to traverse the second list
Node current2 = head2;
// Start position index at 1
int currentPos = 1;
// Pointer to traverse the first list
Node current1 = head1;
while (current1 != null) {
// Get the target position from the first list
int targetPos = current1.data;
// Move the pointer in the second list to the
// target position
while (current2 != null
&& currentPos < targetPos) {
current2 = current2.next;
currentPos++;
}
// Print the node data if it matches the target
// position
if (current2 != null
&& currentPos == targetPos) {
Console.Write(current2.data + " ");
}
// Move to the next node in the first list
current1 = current1.next;
}
Console.WriteLine();
}
static void Main()
{
// Create 1st list: 2 -> 5
Node head1 = new Node(2);
head1.next = new Node(5);
// Create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
Node head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
PrintSecondList(head1, head2);
}
}
JavaScript
class Node {
constructor(x)
{
this.data = x;
this.next = null;
}
}
// Function to print elements of the second list based on
// positions from the first list
function printSecondList(head1, head2)
{
// Pointer to traverse the second list
let current2 = head2;
// Start position index at 1
let currentPos = 1;
// Pointer to traverse the first list
let current1 = head1;
while (current1 !== null) {
// Get the target position from the first list
let targetPos= current1.data;
// Move the pointer in the second list to the target
// position
while (current2 !== null
&& currentPos < targetPos) {
current2 = current2.next;
currentPos++;
}
// Print the node data if it matches the target
// position
if (current2 !== null && currentPos === targetPos) {
process.stdout.write(current2.data + " ");
}
// Move to the next node in the first list
current1 = current1.next;
}
console.log();
}
// Create 1st list: 2 -> 5
let head1 = new Node(2);
head1.next = new Node(5);
// Create 2nd list: 4 -> 5 -> 6 -> 7 -> 8
let head2 = new Node(4);
head2.next = new Node(5);
head2.next.next = new Node(6);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
printSecondList(head1, head2);
Time Complexity: O(m+n), At worst case we would traverse each nodes of both linked list
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem