单向链表归并排序 use Java链表的关键在于递归的时候中间位置的确定,方法是:用两个指针p,f 遍历链表,p走一步而f走两步;当f走完的时候p走到链表的一半!这让我烧绳子那道逻辑题。代码如下/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode sortList(ListNode head) {
ListNode p = head; ListNode f = head.next; while ( f.next !=null && f.next.next !=null ){//locate p at half of the ListNode p = p.next; f = f.next.next; }