cj欧巴周五给讲了核心思想之后做起来就很顺利了。思路很清晰,自己写完
大概分为三步:
1.找中点
2.从中点开始分为左边和右边两个list
3.对两个list进行比较,生成第三个链表
感想:
1. 找中点时的跳出条件是 (fast != null && fast.next != null)
分别对应的是偶数和奇数个值的情况。
而初始值fast = head.next也是为了方便确认跳出情况。如果fast=head的话,链表个数是偶数跳出时,slow就过了中点,不好办啦~
2. 分两边的时候是通过mid.next = null 来把两边手动分开的
3.在获得一个新的链表的时候,插入删除操作不好做就不要做了。直接生成一个新的链表好啦...
另外链表的指针最后是指到链表最后的,所以有了一个dummy和一个tail
/**
* Definition for singly-linked list.* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMiddle(head);
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);
return compare (left, right);
}
public ListNode compare (ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (head1 != null && head2 != null) {
if (head1.val > head2.val) {
tail.next = head2;
head2 = head2.next;
} else {
tail.next = head1;
head1 = head1.next;
}
tail = tail.next;
}
if (head1 != null) {
tail.next = head1;
}
if (head2 != null) {
tail.next = head2;
}
return dummy.next;
}
public ListNode findMiddle(ListNode head) {
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}