题目
对一个无序单向链表进行插入排序。
思想
运用哨兵思想,简化链表边界问题。
示例
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
// 构造哨兵节点
ListNode sentinel = new ListNode(0);
while (head != null) {
ListNode p = sentinel, next = head.next;
while (p.next != null && p.next.val <= head.val) {
p = p.next;
}
// 链表插入
head.next = p.next;
p.next = head;
// 指针重置
head = next;
}
return sentinel.next;
}
}
网友评论