Sort List (Merge Sort)

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;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值