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
2d

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!
Add answer anonymously...
Cleantech Solar Data Analyst Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter