Insertion Sort List (LeetCode)

题目:

Sort a linked list using insertion sort.


思路:

  1. 这题比较简单,题干已经要求用插入排序对链表进行排序
  2. 将链表分为两个部分,一个部分已经排好序,就用head做头结点,另一部分待排序,用toSortList做头结点
    • 令原来链表的一个node作为已排好序的唯一node赋给head
    • 从第二个node开始都是待排序的,所以第二个node为待排序头结点toSortList
    • 切断已排序和未排序的连接,即head.next = null
  3. 每次从待排序中取一个node准备插入已排序链表中,记为temp2
    • 查看待插点temp2的值是否比head的值小,如果是,插到head前面
    • temp1从head开始,遍历已排序链表,找到temp2应该插入的位置,插入




注意点:

  1. java中,类的属性可以迭代调用
    • 例如,temp1.next.val可以读取temp1下一个元素的值



代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode toSortList,temp1,temp2;
        if (head == null){
            return head;
        }
        toSortList = head.next;
        head.next = null;
        while (toSortList != null){
            temp1 = head;
            temp2 = toSortList;
            toSortList = toSortList.next;
            temp2.next = null;
            if (temp2.val <= head.val){
                temp2.next = head;
                head = temp2;
                continue;
            }
            while ((temp1.next != null) && (temp1.next.val < temp2.val)){
                temp1 = temp1.next;
            }
            temp2.next = temp1.next;
            temp1.next =temp2;
        }
        return head;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值