Leetcode: insertion-sort-list

来源:互联网 发布:美工职业描述 编辑:程序博客网 时间:2024/06/05 14:34

题目:

Sort a linked list using insertion sort.


分析:

题目要求用插入排序对一个链表进行排序,那么思路就是构建一个新的链表,将原链表中符合大小条件的结点插入到新链表中。


具体代码的实现如下:


/** * 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 ans = new ListNode(Integer.MIN_VALUE);                        ListNode h = head;                while (h != null){            ListNode p = ans;            while(p.next != null && p.next.val < h.val){                p = p.next;            }                        ListNode next = h.next;                        ListNode tmp = p.next;            p.next = h;            h.next = tmp;                        h = next;        }                return ans.next;    }}


原创粉丝点击