Leetcode刷题java之147. 对链表进行插入排序

执行结果:

通过

显示详情

执行用时 :4 ms, 在所有 Java 提交中击败了96.70% 的用户

内存消耗 :37.4 MB, 在所有 Java 提交中击败了76.87%的用户

题目:

对链表进行插入排序

思路:

其实和数组的插入排序是类似的,只不过,链表只能next,所以遍历后面元素的时候,都要从最开始的位置一个一个比较。而不是从临近的位置一个一个比较。

另外,链表的题不能空想,要动笔,看看哪个连接哪一个,要不容易混乱。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null)
        {
            return head;
        }
        ListNode h=new ListNode(-1);
        h.next=head;
        ListNode pre=h;
        ListNode cur=head;
        ListNode next;
        while(cur!=null)
        {
            next=cur.next;
            if(next!=null&&next.val<cur.val)
            {
                while(pre.next!=null&&next.val>pre.next.val)
                {
                    pre=pre.next;
                }
                ListNode temp=pre.next;
                pre.next=next;
                cur.next=next.next;
                next.next=temp;
                pre=h;
            }else
            {
                cur=next;
            }
        }
        return h.next;
    }
}
发布了438 篇原创文章 · 获赞 440 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/104143207