700572. Linked List that is Sorted Alternatingly
Linked List that is Sorted Alternatingly
Slug: linked-list-that-is-sorted-alternately Difficulty: Medium Id: 700572 Topic Tags: Linked List, Sorting, Data Structures, Algorithms Company Tags: Amazon
Summary
The problem involves creating a sorted linked list where the order of elements alternates between ascending and descending. This means that the first element is in ascending order, the second element is in descending order, the third element is in ascending order again, and so on. The input linked list is not necessarily sorted, but the output linked list should be in the required alternating order.
Detailed Explanation
To solve this problem, we can iterate through the input linked list and create a new linked list while maintaining the alternating order. We will use two pointers, one for the ascending part and one for the descending part, to keep track of the current element being processed.
Here is the step-by-step breakdown:
- Initialize two pointers,
ascanddesc, to point to the first node in the input linked list. - Create a new linked list,
result, with a dummy node as its head. - While there are still nodes left in the input linked list:
- If the current node is less than or equal to the previous node (in ascending order), add it to the ascending part of the result list and move the
ascpointer one step forward. - Else, if the current node is greater than or equal to the previous node (in descending order), add it to the descending part of the result list and move the
descpointer one step forward. - If both parts are exhausted, swap them and continue processing.
- If the current node is less than or equal to the previous node (in ascending order), add it to the ascending part of the result list and move the
- Return the
resultlinked list.
Time complexity: O(n), where n is the number of nodes in the input linked list. Space complexity: O(n), for the new linked list being created.
Optimized Solutions
Java
class Solution {
public ListNode sortedAlternately(ListNode head) {
ListNode result = new ListNode(0);
ListNode asc = head, desc = null;
while (asc != null || desc != null) {
if (asc != null) {
result.next = asc;
asc = asc.next;
}
if (desc == null && asc != null) {
desc = asc;
asc = asc.next;
} else if (desc != null) {
result.next = new ListNode(desc.val);
result = result.next;
desc = desc.next;
}
}
return result.next;
}
}