题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

插入排序O(n ^ 2)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        if(head == null) return null;
        if(head.next == null) return head;
        ListNode cur = head.next , ans = new ListNode(head.val);
        while(cur != null) {
            ListNode th = ans , pre = null;
            if(cur.val <= th.val) {
                ListNode temp = new ListNode(cur.val);
                temp.next = ans;
                ans = temp;
            }else {
                while(th != null && cur.val > th.val) {
                    pre = th;
                    th = th.next;
                }
                pre.next = new ListNode(cur.val);
                pre.next.next = th;
            }
            cur = cur.next;
        }
        return ans;
    }
}
全部评论

相关推荐

今天 13:29
已编辑
门头沟学院 Java
北斗导航Compass低仿版:能不能先搞清楚优先级啊,怎么可能是项目问题,项目很重要吗?又没学历 又没实习大厂凭啥约面?那玩具项目 没应用在真实生产环境下的 就算做上天又有什么用?早点找个小公司实习 拿小公司实习去投大厂实习,这才是你现在该做的
投递美团等公司9个岗位 简历被挂麻了,求建议
点赞 评论 收藏
分享
群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务