Merge Sort Linked List

Given a singly-linked list, where each node contains an integer value, sort it in ascending order. The merge sort algorithm should be used to solve this problem.

Examples

null, is sorted to null
1 -> null, is sorted to 1 -> null
1 -> 2 -> 3 -> null, is sorted to 1 -> 2 -> 3 -> null
4 -> 2 -> 6 -> -3 -> 5 -> null, is sorted to -3 -> 2 -> 4 -> 5 -> 6

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
  def mergeSort(self, head):
    if head is None or head.next is None:
      return head
    head1,head2 = self.split(head)
    p = self.mergeSort(head1)
    q = self.mergeSort(head2)
    return self.merge(p,q)
    """
    input: ListNode head
    return: ListNode
    """
    # write your solution here
  def split(self,head):
    p = head
    q = ListNode(None)
    cur = head
    length = 0
    while cur:
      cur = cur.next
      length += 1
    mid = length/2
    count = 1
    while p is not None:
      if count == mid:
        q.next = p.next
        p.next = None
      p = p.next
      count += 1
    return head,q.next
  
  def merge(self,p,q):
    head = cur = ListNode(0)
    while p and q:
      if p.val > q.val:
        cur.next = q
        q = q.next
      else:
        cur.next = p
        p = p.next
      cur = cur.next
    cur.next = p or q
    return head.next
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 1、报名提交材料 层级 提交材料 高起专 1、二代身份证正反面扫描件(无需原件扫描); 2、中专、技校、高中等学历...
    现任男友阅读 1,923评论 0 0
  • 7月末八月初的时候,我在连城自然保护区的松树林里见到了一种极难见到的腐生植物——松下兰(学名:Monotropa ...
    彩南花槿阅读 7,307评论 2 2
  • 清晨四点,我已醒来。窗外蒙蒙黑,那就开灯看会儿书。等着天光将至,起身,换上长裙与丝质衬衫,推门往外而去。 珠海的清...
    shaoman413阅读 245评论 0 1