链表的插入排序(Leetcode147)

2018-11-11  本文已影响0人  zhouwaiqiang

题目

解法

代码实现

/**
 * 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 front = new ListNode(0);
        front.next = head;
        ListNode index = head.next;
        ListNode indexPre = head;
        while (index != null) {
            ListNode insertPre = front;
            ListNode temp = front.next;
            while (temp.val < index.val) {
                insertPre = temp;
                temp = temp.next;
            }
            if (temp != index) {
                indexPre.next = index.next;
                index.next = insertPre.next;
                insertPre.next = index;
                index = indexPre.next;
            } else {
                indexPre = index;
                index = index.next;
            }
        }
        return front.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读