# 排序链表

<p>给你链表的头结点 <code>head</code> ，请将其按 <strong>升序</strong> 排列并返回 <strong>排序后的链表</strong> 。</p>

<p><b>进阶：</b></p>

<ul>
	<li>你可以在 <code>O(n log n)</code> 时间复杂度和常数级空间复杂度下，对链表进行排序吗？</li>
</ul>

<p> </p>

<p><strong>示例 1：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/f2b8957105894d4fe9ffe9462e65f8e8.jpeg" style="width: 302px; "/>
<pre>
<b>输入：</b>head = [4,2,1,3]
<b>输出：</b>[1,2,3,4]
</pre>

<p><strong>示例 2：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/f10bc169c916b5b0bc8651e5f7e99492.jpeg" style="width: 402px; " />
<pre>
<b>输入：</b>head = [-1,5,3,4,0]
<b>输出：</b>[-1,0,3,4,5]
</pre>

<p><strong>示例 3：</strong></p>

<pre>
<b>输入：</b>head = []
<b>输出：</b>[]
</pre>

<p> </p>

<p><b>提示：</b></p>

<ul>
	<li>链表中节点的数目在范围 <code>[0, 5 * 10<sup>4</sup>]</code> 内</li>
	<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>


## template

```java
public class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
}

class Solution {
	public ListNode sortList(ListNode head) {

		if (head == null)
			return head;

		return mergeSort(head);
	}

	public ListNode mergeSort(ListNode head) {

		if (head.next == null)
			return head;

		ListNode p1 = head;
		ListNode p2 = head.next;

		if (p2 != null && p2.next != null) {
			p1 = p1.next;
			p2 = p2.next.next;
		}
		ListNode left = head;
		ListNode right = p1.next;
		p1.next = null;

		left = mergeSort(left);
		right = mergeSort(right);

		return merge(left, right);
	}

	public ListNode merge(ListNode left, ListNode right) {

		ListNode head = null;

		if (left.val < right.val) {
			head = left;
			left = left.next;
		} else {
			head = right;
			right = right.next;
		}
		ListNode tmp = head;

		while (left != null && right != null) {
			if (left.val < right.val) {
				tmp.next = left;
				left = left.next;
			} else {
				tmp.next = right;
				right = right.next;
			}
			tmp = tmp.next;
		}

		tmp.next = left != null ? left : right;
		return head;
	}
}

```

## 答案

```java

```

## 选项

### A

```java

```

### B

```java

```

### C

```java

```