LeetCode 0148. Sort List Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0148. Sort List

Description

Given the head of a linked list, return the list after sorting it in ascending order.

 

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2:

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Example 3:

Input: head = []
Output: []

 

Constraints:

  • The number of nodes in the list is in the range [0, 5 * 104].
  • -105 <= Node.val <= 105

 

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

Solutions

Solution 1: Merge Sort

We can use the merge sort approach to solve this problem.

First, we use the fast and slow pointers to find the middle of the linked list and break the list from the middle to form two separate sublists l1 and l2.

Then, we recursively sort l1 and l2, and finally merge l1 and l2 into a sorted linked list.

The time complexity is O(n × log n), and the space complexity is O(log n). Here, n is the length of the linked list.

PythonJavaC++GoTypeScriptRustJavaScriptC#
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None or head.next is None: return head slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next l1, l2 = head, slow.next slow.next = None l1, l2 = self.sortList(l1), self.sortList(l2) dummy = ListNode() tail = dummy while l1 and l2: if l1.val <= l2.val: tail.next = l1 l1 = l1.next else: tail.next = l2 l2 = l2.next tail = tail.next tail.next = l1 or l2 return dummy.next(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !