
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)
Editorial
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. | ||||
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.