leetCode---链表专题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/duoduo18up/article/details/79971196

题目描述1    单链表排序问题

Sort a linked list in O(n log n) time using constant space complexity.


用归并排序:  其中只是创建了一个preHead节点 占用空间O(1)    时间O(nlogn)

public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }  //常规合并排序思路
        ListNode mid = getMid(head);
        ListNode midNext = mid.next;
        mid.next = null;                      //一定记得断开head 左半部分的链表尾部
        return mergeSort(sortList(head), sortList(midNext));
    }
    private ListNode getMid(ListNode head) {         //使用快慢指针获取中间节点位置
        if(head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, quick = head;
        while(quick.next != null && quick.next.next != null) {
            slow = slow.next;
            quick = quick.next.next;
        }
        return slow;
    }
    private ListNode mergeSort(ListNode n1, ListNode n2) {    对两个分链表进行合并
        ListNode preHead = new ListNode(0), cur1 = n1, cur2 = n2, cur = preHead;
        while(cur1 != null && cur2 != null) {
            if(cur1.val < cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            } else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        cur.next = cur1 == null ? cur2 : cur1;     //看哪个链表不为空 继续接上
        return preHead.next;
    }
}

用快速排序:


public class Solution {
    public ListNode sortList(ListNode head) {
        quickSort(head, null);
        return head;
    }
 
    public static void quickSort(ListNode head, ListNode end) {
        if(head != end) {
            ListNode partion = partion(head,end);
            quickSort(head, partion);
            quickSort(partion.next, end);
        }
    }
 
    public static ListNode partion(ListNode head, ListNode end) {
        ListNode slow = head; 
        ListNode fast = head.next;
        while (fast != end) {
            if(fast.val < head.val) { 
                slow = slow.next;
                int temp=slow.val;     //交换slow和fast的值
                slow.val=fast.val;
                fast.val=temp;
            }
            fast = fast.next;
        }
        int temp=head.val; //交换slow和最初基准值
        head.val=slow.val;
        slow.val=temp;
        return slow;
    }
}

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页