Merging Sorted Linked Lists With Merge Sort Algorithm
Merging two sorted linked lists using merge sort algorithm. The `sortList` method splits the list into smaller chunks, sorts each chunk recursively and then merges them back together in sorted order.
problem
note: the sort() method can be used to merge to sorted linked list
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
// using merge sort on the given list
return merge(head);
}
public ListNode merge(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode middleNod...