//Sort a linked list using insertion sort.
//
//
//
//
//
//A graphical example of insertion sort. The partial sorted list (black) initial
//ly contains only the first element in the list.
//With each iteration one element (red) is removed from the input data and inser
//ted in-place into the sorted list
//
//
//
//
//
// Algorithm of Insertion Sort:
//
//
// Insertion sort iterates, consuming one input element each repetition, and gro
//wing a sorted output list.
// At each iteration, insertion sort removes one element from the input data, fi
//nds the location it belongs within the sorted list, and inserts it there.
// It repeats until no input elements remain.
//
//
//
//Example 1:
//
//
//Input: 4->2->1->3
//Output: 1->2->3->4
//
//
// Example 2:
//
//
//Input: -1->5->3->4->0
//Output: -1->0->3->4->5
//
// Related Topics 排序 链表
// 👍 247 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
return null;
}
ListNode root = new ListNode(-1);
root.next = head;
ListNode t = root.next;
ListNode pre = root;
while (t != null) {
ListNode temp = t;
ListNode p = root;
ListNode q = root.next;
boolean flag = false;
while (p != null && q != null && q != temp) {
if (q.val > temp.val) {
pre.next = temp.next;
p.next = temp;
p.next.next = q;
flag = true;
break;
}
p = p.next;
q = q.next;
}
if (flag) {
t = pre.next;
} else {
t = t.next;
pre = pre.next;
}
}
return root.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
leetcode147-Insertion Sort List
最新推荐文章于 2024-04-28 16:03:45 发布