Insertion Sort in a Linked List

Given a singly linked list with 'N' nodes containing integer values, your task is to sort the list using insertion sort and output the sorted list.

Insertion Sort is an algorithm where elements are removed one at a time from the input data, positioned in their correct location within a growing sorted list, and this process continues until no unsorted elements remain.

Input:

The first line contains an integer T, representing the number of test cases.
The subsequent lines for each test case contain space-separated integers representing the elements of the linked list, ending with -1.
Note that -1 is used to mark the end of the list and is not a list element.

Output:

For each test case, print the sorted linked list elements as space-separated integers.
Output each sorted list on a new line for every test case.

Example:

Input:
2
4 3 2 10 -1
1 7 5 2 -1
Output:
2 3 4 10
1 2 5 7

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 103
  • 0 <= value of node < 109
Note:
You are not required to print the results yourself; handle only the function implementation. Aim to sort the linked list in-place.
AnswerBot
4mo

Implement insertion sort on a singly linked list to sort the elements in-place.

  • Iterate through the linked list and for each node, find its correct position in the sorted part of the list

  • Adjust pointer...read more

Help your peers!
Select
Add answer anonymously...

Cleantech Solar Data Analyst Intern interview questions & answers

A Data Analyst Intern was asked Q. Balls picking probability problem
A Data Analyst Intern was asked Q. Water Jug Problem Statement You have two water jugs with capacities X and Y lite...read more
A Data Analyst Intern was asked Q. Insertion Sort in a Linked List Given a singly linked list with 'N' nodes contai...read more

Popular interview questions of Data Analyst Intern

A Data Analyst Intern was asked Q1. Balls picking probability problem
A Data Analyst Intern was asked Q2. Insertion Sort in a Linked List Given a singly linked list with 'N' nodes contai...read more
A Data Analyst Intern was asked Q3. What is the difference between loc and iloc in data science, and can you explain...read more
Cleantech Solar Data Analyst Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits