使用快速排序算法对列表进行排序——Leetcode系列(四)
来源:互联网 发布:企业应用开发实战源码 编辑:程序博客网 时间:2024/06/05 00:53
Sort a linked list in O(n log n) time using constant space complexity.
My Answer:
/** * 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) { if(head == null){ return head; } ListNode pivot = head; ListNode pre = null; ListNode first = null; ListNode last = null; pivot = head; while(pivot != null){ if(pivot.val < head.val){ pre.next = pivot.next; pivot.next = first; first = pivot; pivot = pre; }else if(pivot.val > head.val){ pre.next = pivot.next; pivot.next = last; last = pivot; pivot = pre; } pre = pivot; pivot = pivot.next; } first = sortList(first); last = sortList(last); pivot = head; while(pivot != null){ pre = pivot; pivot = pivot.next; } pre.next = last; if (first == null){ return head; } pivot = first; while(pivot != null){ pre = pivot; pivot = pivot.next; } pre.next = head; return first; }}
题目来源: https://oj.leetcode.com/problems/sort-list/
0 0
- 使用快速排序算法对列表进行排序——Leetcode系列(四)
- 使用插入排序算法对列表进行排序——Leetcode系列(五)
- 基础算法系列(四)——快速排序
- 排序算法系列——快速排序
- 排序算法(四)——快速排序
- 算法——排序(四)快速排序
- 排序算法(四)快速排序算法
- 算法系列(四)排序算法中篇--归并排序和快速排序
- 对列表进行排序
- 列表重新排序——Leetcode系列(八)
- 使用快速排序算法对字符串数组进行排序(复习指向指针的指针以及指针数组的使用)
- 排序算法(四):快速排序
- 排序算法(四)-- 快速排序
- Java排序算法(四):快速排序
- 经典算法系列—— 快速排序
- 快速排序----(排序算法四)
- 排序算法(四):快速排序
- 排序算法系列:快速排序
- jquery ztree 3.4 基本使用
- WaitForSingleObject
- POJ 2226 Muddy Fields 二分匹配
- OpenGl
- 高性能WEB开发 - 图片篇
- 使用快速排序算法对列表进行排序——Leetcode系列(四)
- webwork 集合自动赋值
- WaitForSingleObject介绍
- ireport crosstab header
- C++面试汇总
- 【Kinect开发笔记之(二)】Kinect for windows发展历程
- softmax
- 第七讲:HTML5中的canvas两个小球完全弹性碰撞
- jquery.ui.dialog 1.81在IE8中出现滚动条bug解决方法