letcode每日一题-对链表进行插入排序

今天的每日一题主要考验了链表的操作和插入排序,综合来说还是简单的,记录一下!!

题目描述:


代码实现如:

public ListNode insertionSortList(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode headPoint=new ListNode(-1);
        headPoint.next=head;
        ListNode LastSorted=head,curr=head.next;
        while (curr!=null){
            if(curr.val>=LastSorted.val){
                LastSorted=curr;
            }else{
                ListNode prev=headPoint;
                while(prev.next.val<=curr.val){
                    prev=prev.next;
                }
                LastSorted.next=curr.next;
                curr.next=prev.next;
                prev.next=curr;
            }
            curr=LastSorted.next;
        }
        return headPoint.next;
    }

思路:
1.应为这个题目的链表是单向的,所以可以设置一个头结点指向链表,这样更便于操作
2.手绘了几个步骤,大致如下:
链表[4,3,2,1]

posted @ 2020-11-20 10:32  CodeWangHAHA  阅读(69)  评论(0编辑  收藏  举报