700572. Linked List that is Sorted Alternatingly

Medium

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:

  1. Initialize two pointers, asc and desc, to point to the first node in the input linked list.
  2. Create a new linked list, result, with a dummy node as its head.
  3. 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 asc pointer 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 desc pointer one step forward.
    • If both parts are exhausted, swap them and continue processing.
  4. Return the result linked 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

View on GeeksforGeeks
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;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.