Insertion Sort List

Description:

Sort a linked list using insertion sort.

问题描述:

插入排序给一条链表元素排序

解法一:

思路:

将链表元素一个一个的切下来,利用两个指针,一个排好序链表的表头指针(sortedHead),一个排好序链表的表尾指针。
插入结点时分为三种情况:
+ 待插入元素比新表表头元素小
+ 待插入元素比新表表尾大
+ 待插入元素在新表表头和新表表尾之间,这个时候就要找到比待插入元素刚好大的最近结点

Code:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head ==null || head.next == null)
            return head;

        ListNode sortedHead = head, sortedTail = head;
        head = head.next;
        sortedHead.next = null;

        while(head != null){
            ListNode temp = head;
            head = head.next;
            temp.next = null;

            //new val is less than the head , just insert in the front
            if( temp.val <= sortedHead.val){
                temp.next = sortedHead;
                sortedTail = (sortedHead == null) ? sortedHead : sortedTail;
                sortedHead = temp;
            }
            //new val is greater than the tail, just insert in the back    
            else if(temp.val >= sortedTail.val){
                sortedTail.next = temp;
                sortedTail = sortedTail.next;
            }
            //new val is somewhere in the middle , we will have to find its proper location
            else{
                ListNode current = sortedHead;
                while(current.next != null && current.next.val < temp.val){
                    current = current.next;
                }
                temp.next = current.next;
                current.next = temp;
            }


        }
        return sortedHead;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值