美文网首页
lint0173. Insertion Sort List

lint0173. Insertion Sort List

作者: 日光降临 | 来源:发表于2019-03-03 21:42 被阅读0次
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);
        // 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里
        // 所以这里不需要dummy.next = head;

        while (head != null) {
            ListNode node = dummy;
            while (node.next != null && node.next.val < head.val) {
                node = node.next;
            }
            ListNode temp = head.next;
            head.next = node.next;
            node.next = head;
            head = temp;
        }

        return dummy.next;
    }
}

相关文章

网友评论

      本文标题:lint0173. Insertion Sort List

      本文链接:https://www.haomeiwen.com/subject/kdtvuqtx.html