Tutorialspoint
Problem
Solution
Submissions

Rearramge Linked List

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to rearrange a linked list in alternating ascending/descending order. Given a singly linked list, rearrange it such that the first node is the smallest, the second node is the largest, the third node is the second smallest, the fourth node is the second largest, and so on. The rearrangement should be done in-place without altering the values in the nodes.

Example 1
  • Input: 1->2->3->4->5
  • Output: 1->5->2->4->3
  • Explanation:
    • The smallest element is 1, the largest is 5, the second smallest is 2, the second largest is 4, and the third smallest is 3.
Example 2
  • Input: 5->9->2->8->1->6
  • Output: 1->9->2->8->5->6
  • Explanation:
    • The smallest element is 1, the largest is 9, the second smallest is 2, the second largest is 8, the third smallest is 5, and the third largest is 6.
Constraints
  • The number of nodes in the linked list is between 1 and 10^5
  • -10^5 ≤ Node.val ≤ 10^5
  • Time Complexity: O(n log n)
  • Space Complexity: O(1) for the rearrangement (excluding the sorting step)
Linked ListHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the linked list first using merge sort (to maintain O(n log n) time complexity).
  • Split the sorted list into two halves.
  • Reverse the second half of the linked list.
  • Merge the two halves alternately.
  • Take care of edge cases when the list has 0, 1, or 2 nodes.

Steps to solve by this approach:

 Step 1: Sort the linked list using merge sort to ensure O(n log n) time complexity.
 Step 2: Find the middle point of the sorted list to split it into two halves.
 Step 3: Reverse the second half of the list so that it goes from largest to smallest.
 Step 4: Merge the two halves alternately - first from the first half, then from the reversed second half.
 Step 5: Handle edge cases where the list has 0, 1, or 2 nodes separately.
 Step 6: Ensure that the pointers are correctly modified during the merging process.
 Step 7: Return the head of the rearranged linked list.

Submitted Code :