Grokking Data Structures & Algorithms for Coding Interviews
Vote
0% completed
Sort List (medium)
Problem Statement
Given a head of the linked list, return the list after sorting it in ascending order.
Examples
-
Example 1:
- Input:
[3, 1, 2] - Expected Output:
[1, 2, 3] - Justification: The list is sorted in ascending order, with
1coming before2, and2before3.
- Input:
-
Example 2:
- Input:
[4] - Expected Output:
[4] - Justification: A list with a single element is already sorted.
- Input:
-
Example 3:
- Input:
[9, 8, 7, 6, 5, 4, 3, 2, 1] - Expected Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- Input:
.....
.....
.....
Like the course? Get enrolled and start learning!
S
Syed Ahmed
· 3 years ago
public ListNode sortList(ListNode head) { if(head==null){ return head; } ListNode current = head; ListNode next = head.next; while(next != null){ if(next.val <= current.val){ int temp = next.val; next.val = current.val; current.val = temp; } if(next.next== null){ current = current.next; next = current.next; }else{ next = next.next; } } return head; }
Reading Progress
0%